Introduction:
Here I will explain how to get checkbox selected gridview
row values in asp.net using C#
and VB.NET or get row values from gridview
when checkbox selected in asp.net
using C# and VB.NET.
Description:
In previous articles I explained Asp.net Interview questions, Export Gridview data to PDF, Send values from one page to another page using QueryString,
Joins in SQL Server, Highlight Gridview records based on search and many
articles relating to Gridview,
SQL, jQuery,asp.net,
C#,VB.NET.
Now I will explain how to get row values from gridview
when checkbox selected asp.net
using C# and VB.NET.
To get checkbox selected row values
from gridview we need to write the code like this
C#
Code
foreach(GridViewRow gvrow in
gvDetails.Rows)
{
CheckBox chk = (CheckBox)gvrow.FindControl("chkSelect");
if (chk != null &
chk.Checked)
{
str +=
gvDetails.DataKeys[gvrow.RowIndex].Value.ToString() + ',';
strname += gvrow.Cells[2].Text+',';
}
}
|
VB.NET
Code
For Each gvrow As GridViewRow In gvDetails.Rows
Dim chk As CheckBox = DirectCast(gvrow.FindControl("chkSelect"), CheckBox)
If chk IsNot Nothing And
chk.Checked Then
str += gvDetails.DataKeys(gvrow.RowIndex).Value.ToString()
+ ","c
strname += gvrow.Cells(2).Text & ","c
End If
Next
|
If you want to see complete example
we need to write the following code in aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Get
Checkbox Selected Row Values from Gridview in Asp.net</title>
</head>
<body>
<form id="form1"
runat="server">
<div>
<asp:GridView ID="gvDetails" DataKeyNames="UserId" AutoGenerateColumns="false" CellPadding="5" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="UserId" DataField="UserId" />
<asp:BoundField HeaderText="UserName" DataField="UserName" />
<asp:BoundField HeaderText="Education" DataField="Education" />
<asp:BoundField HeaderText="Location" DataField="Location" />
</Columns>
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
<asp:Button ID="btnProcess" Text="Get Selected Records" runat="server"
Font-Bold="true" onclick="btnProcess_Click" /><br />
<asp:Label ID="lblmsg" runat="server" />
</div>
</form>
</body>
</html>
|
Now in code behind add the following namespaces
C#
Code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
|
Now add below code in code
behind
protected void
Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridviewData();
}
}
protected void
BindGridviewData()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId",
typeof(Int32));
dt.Columns.Add("UserName",
typeof(string));
dt.Columns.Add("Education",
typeof(string));
dt.Columns.Add("Location",
typeof(string));
DataRow dtrow = dt.NewRow(); // Create New
Row
dtrow["UserId"]
= 1; //Bind Data to Columns
dtrow["UserName"]
= "SureshDasari";
dtrow["Education"]
= "B.Tech";
dtrow["Location"]
= "Chennai";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow(); //
Create New Row
dtrow["UserId"]
= 2; //Bind Data to Columns
dtrow["UserName"]
= "MadhavSai";
dtrow["Education"]
= "MBA";
dtrow["Location"]
= "Nagpur";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow(); //
Create New Row
dtrow["UserId"]
= 3; //Bind Data to Columns
dtrow["UserName"]
= "MaheshDasari";
dtrow["Education"]
= "B.Tech";
dtrow["Location"]
= "Nuzividu";
dt.Rows.Add(dtrow);
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
protected void
btnProcess_Click(object sender, EventArgs e)
{
string str = string.Empty;
string strname = string.Empty;
foreach(GridViewRow gvrow in
gvDetails.Rows)
{
CheckBox chk = (CheckBox)gvrow.FindControl("chkSelect");
if (chk != null &
chk.Checked)
{
str += gvDetails.DataKeys[gvrow.RowIndex].Value.ToString()
+ ',';
strname += gvrow.Cells[2].Text+',';
}
}
str= str.Trim(",".ToCharArray());
strname = strname.Trim(",".ToCharArray());
lblmsg.Text = "Selected
UserIds: <b>" + str + "</b><br/>"
+ "Selected UserNames: <b>"
+ strname+"</b>";
}
|
VB.NET
Code
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.UI.WebControls
Partial Class VBCode
Inherits System.Web.UI.Page
Protected Sub
Page_Load(sender As Object,
e As EventArgs)
Handles Me.Load
If Not IsPostBack Then
BindGridviewData()
End If
End Sub
Protected Sub
BindGridviewData()
Dim dt As New DataTable()
dt.Columns.Add("UserId",
GetType(Int32))
dt.Columns.Add("UserName",
GetType(String))
dt.Columns.Add("Education",
GetType(String))
dt.Columns.Add("Location",
GetType(String))
Dim dtrow As DataRow = dt.NewRow()
' Create New Row
dtrow("UserId")
= 1
'Bind Data to Columns
dtrow("UserName")
= "SureshDasari"
dtrow("Education")
= "B.Tech"
dtrow("Location")
= "Chennai"
dt.Rows.Add(dtrow)
dtrow = dt.NewRow()
' Create New Row
dtrow("UserId")
= 2
'Bind Data to Columns
dtrow("UserName")
= "MadhavSai"
dtrow("Education")
= "MBA"
dtrow("Location")
= "Nagpur"
dt.Rows.Add(dtrow)
dtrow = dt.NewRow()
' Create New Row
dtrow("UserId")
= 3
'Bind Data to Columns
dtrow("UserName")
= "MaheshDasari"
dtrow("Education")
= "B.Tech"
dtrow("Location")
= "Nuzividu"
dt.Rows.Add(dtrow)
gvDetails.DataSource = dt
gvDetails.DataBind()
End Sub
Protected Sub
btnProcess_Click(sender As Object, e As EventArgs)
Dim str As String = String.Empty
Dim strname As String = String.Empty
For Each gvrow As GridViewRow In gvDetails.Rows
Dim chk As CheckBox = DirectCast(gvrow.FindControl("chkSelect"), CheckBox)
If chk IsNot Nothing And
chk.Checked Then
str +=
gvDetails.DataKeys(gvrow.RowIndex).Value.ToString() + ","c
strname += gvrow.Cells(2).Text & ","c
End If
Next
str = str.Trim(",".ToCharArray())
strname = strname.Trim(",".ToCharArray())
lblmsg.Text = "Selected
UserIds: <b>" & str & "</b><br/>"
& "Selected UserNames: <b>"
& strname & "</b>"
End Sub
End Class
|
Demo
If you enjoyed this post, please support the blog below. It's FREE! Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email. |
|||
|
|||
34 comments :
very use full post to the developers,U r blog has very nice examples
Thank u very much Sir. from Narsimha
@Krishna Kumar,
Thanks for your kind notification. Actually those ads are coming from google adsense. I already sent request to remove those ads.
hai suresh.. ur blogs are very useful for my projects.. i used ur codings in my project.. it helps a lot..
now i want to use approval workflow in windows workflow foundation in asp.net.. i refered many sites but i can't understand clearly..
would you help me please..
its urgent.. please help me sir..
thanks in advance..
Hello sir,
is there any property for setting header text for template field(as u have explain Checkbox template)
send me reply on wis_134@yahoo.com
Thank you
pls any 1 help me for implementing approval workflow in wwf.......
plzzzzzzzzzzzz
hi sir
wt is wcf and when and where is used wcf?
DIFFERENCE BETWEEN THE EXCUTE READER AND EXCUTE NON QUERY?
PLZ HELP ME
i don't know whether you are checked in my site using search or not. i written all the articles if you want anything check through search. Please check this article http://www.aspdotnet-suresh.com/2012/09/differences-between-executereader.html
thnks it is useul
hi sir
please tell me one problem
How to bind each line of text from textbox in each row of gridview
Sir, can you tell me how to get the values of a row in a gridview and display in next page?
Sir, Can you tell me how to get the values of a row in a gridview and display in next page
sir, the check box control was refreshed when i get click the submit button. how to resolve it.
good
Hello,Sir
I am new to c#.net and I am developing online examination website,during this i got the problem that when we display the list of questions and selected que. from gridview should be appear in exam how it is possible .Can you provide me code snnepts for better guidence?
I have to submit my project within three days ,Please sir HELP ME.
THANK YOU
thanks bro, for this nice work.
hi suresh ur articles are very very nice and useful to software engineers... i think your search option is not working properly.....plz check once yaar
hi suresh search option is not working properly iam not able to find out my required article by using search option.....plz check once yaar
here you retrive the data from grid.can you show me how to display that datas into dropdownlist
Sir, i want to display only selected content.. that means I need to display only query based content.. Example, if i give a query as exam means the exam content only i need to display.. thank u.
Thanks for the article
but when we select checkbox from mulitple pages of gridview we get only values of current page.
Hi suresh,
i have debug,
my problem is i am using a asp gridview with templatefields in that i have a checkbox .
wheather i want to checked the checkbox and inserting into database table,
how can i store the checked checkbox value..
table
--------
firstname nvarchar(40)
lastname nvarchar(40)
place nvarchar(20)
active bit
Suresh could u please tell me how to return last row data of a grid view into label
hello sir , when i try to cast it give exception like this
"Unable to cast object of type 'System.Web.UI.WebControls.GridViewRow' to type 'System.Web.UI.WebControls.GridView'."
whhile my code is like this
for data in gridview
private void show()
{
con = new SqlConnection(str);
con.Open();
cmd = new SqlCommand("select * from info", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GvShow.DataSource = ds;
GvShow.DataBind();
}
and on button click
string strid = string.Empty;
string strname = string.Empty;
foreach(GridView gds in GvShow.Rows)
{
CheckBox chb = (CheckBox)gds.FindControl("chk");
}
getting error.
Object reference not set to an instance of an object.
foreach (GridViewRow gridviewrow in grv.Rows)
{
}
sir as many other article there is option for download the code , but some of your article doesn't have option for download. can we have a download option for all aritcle
Thanks, it is working fine for me.
my code behind page is :
protected void btnSend_Click(object sender, EventArgs e)
{
string str = "";
string strname = "";
foreach(GridViewRow gvrow in grdUserData.Rows)
{
CheckBox chk = (CheckBox)gvrow.FindControl("chkSelect");
if (chk != null & chk.Checked)
{
str += grdUserData.DataKeys[gvrow.RowIndex].Value.ToString() + ',';
strname += gvrow.Cells[2].Text + ',';
}
}
str= str.Trim(",".ToCharArray());
strname = strname.Trim(",".ToCharArray());
lblString.Text = "Selected UserIds: " + str + "
" + "Selected UserNames: " + strname+"";
}
and my gridview is:
i am getting this error :
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
Thanks a lot bro!!! i m so happy to got your article.!!! As i m that much confuse to see lots of way that may distract me from my goal.!!! I greatly thanks to you bro!!! :)
suresh can u give me source code of integerating ccavenue payment project .
In Master page using ModalPopUpExtender did not work..... CheckBox.Checked.. all time CheckBox.Check=false
it is vert useful
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
why this type of error message showed i am using your code kindly please help me
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
foreach(GridViewRow gvrow in gvDetails.Rows)
{
CheckBox chk = (CheckBox)gvrow.FindControl("chkSelect");
if (chk != null & chk.Checked)
{
str += gvDetails.DataKeys[gvrow.RowIndex].Value.ToString() + ',';
strname += gvrow.Cells[2].Text+',';
}
}
Sir in this code you have bind checkbox control to "chk" where how can we check "if (chk != null & chk.Checked)" value as a true? if it will be true then and then only if block code will be executed..
i debug this code but every time i am getting checkbox values false(as default value) and if condition code not working at all and debugger skip that if condition block
Note: Only a member of this blog may post a comment.