Gridview Boundfield and checkbox

I have a gridview that is populated from a database.  The gridview has a checkbox in an ItemTemplate field.  I want to loop through the gridview, find the rows that have been checked, extract the value from a boundfield in the gridview and pass this value to a stored procedure that updates the database.

I have the code to loop through the gridview to see if the row is check and the code to update the database, however, I need the correct code to extract the value from the boundfield.  I tried using something similar to "TextBox2.Text = GridView2.SelectedRow.Cells(2).Text", however, I receive an error message because the row is not selected.

Any assistance would be greatly appreciated.
akajtAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ddayx10Commented:
If I understand you correctly then when you are looping through the gridview you need to find the appropriate index position in the row, and pull the value that way.

EX.
GridView2.Rows(1).Cells(2).Text

Of course you can't just throw numbers in for index positions, you will have to integrate this into your loop. You can just test it with the above type of code until you find the right location and adjust your logic accordingly.

Alternately if that proves cumbersome for you then you might just put a hidden field of some type in the itemtemplate with the checkbox, bind the value you are looking for to that, and get it from the template as you determine if the checkbox is checked or not??
0
jinalCommented:
Try my attached sample . This will help you out.

/* ASPX */ 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default10.aspx.cs" Inherits="Default10" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
           <Columns>
               <asp:TemplateField>
                    <ItemTemplate>
                     <asp:CheckBox runat="server" ID="chkSelected"/>
                    </ItemTemplate>
               </asp:TemplateField>
               <asp:BoundField DataField="ID" HeaderText="ID" />
               <asp:BoundField DataField="Name" HeaderText="Name" />
           </Columns>
        </asp:GridView>
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Submit" />
    </div>
    </form>
</body>
</html>
 
/* Code Behind */
 
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
 
public partial class Default10 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            GridView1.DataSource = CreateParentTable();
            GridView1.DataBind();
        }
    }
 
    private DataTable CreateParentTable()
    {
 
        DataTable dtParent = new DataTable("Parent");
        dtParent.Columns.Add("ID");
        dtParent.Columns.Add("Name");
 
        DataRow dr = dtParent.NewRow();
        dr["ID"] = "1";
        dr["Name"] = "test1";
        dtParent.Rows.Add(dr);
 
        dr = dtParent.NewRow();
        dr["ID"] = "2";
        dr["Name"] = "test2";
        dtParent.Rows.Add(dr);
 
        return dtParent;
    }
 
    protected void Button1_Click(object sender, EventArgs e)
    {
        List<int> ids = new List<int>();
        List<string> names = new List<string>();
        foreach (GridViewRow gRow in GridView1.Rows)
        {
            CheckBox chk = gRow.FindControl("chkSelected") as CheckBox;
            if (chk.Checked)
            {
                Response.Write(gRow.Cells[1].Text + ",");
                ids.Add(int.Parse(gRow.Cells[1].Text));
                names.Add(gRow.Cells[2].Text);
            }
        }
        
    }
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ddayx10Commented:
I changed your GridView around just slightly to accomodate my devTable, but the layout is the same. This should give you the idea of how to get at the data your looking at (see snippet).
****ASPX CODE****
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
           <Columns>
               <asp:TemplateField>
                    <ItemTemplate>
                     <asp:CheckBox runat="server" ID="chkSelected"/>
                    </ItemTemplate>
               </asp:TemplateField>
               <asp:BoundField DataField="testid" HeaderText="ID" />
               <asp:BoundField DataField="fName" HeaderText="First Name" />
           </Columns>
        </asp:GridView>
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Submit" />
        
        <span>Checked Row Values Here: </span>
        <asp:TextBox ID="txtResults" runat="server" />
    </form>
</body>
</html>
 
 
****CODE BEHIND****
 
    private string connStr
    {
        get { return ConfigurationManager.ConnectionStrings["conn"].ToString(); }
    }
 
 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack) bindToGrid();
    }
 
    
    protected void Button1_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow gRow in GridView1.Rows)
        {
            CheckBox rb = (CheckBox)gRow.Cells[0].Controls[1];
            if (rb.Checked)
            {
                txtResults.Text += "[ " + gRow.Cells[1].Text + "/" + gRow.Cells[2].Text + " ] - ";
            }
        }
 
        //being lazy or I would remove the ending "-" from txtResults above code causes.
    }
 
 
    private void bindToGrid()
    {
        SqlConnection conn = new SqlConnection(connStr);
        SqlCommand cmd = new SqlCommand("SELECT * FROM DevTable", conn);
        conn.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        GridView1.DataSource = dr;
        GridView1.DataBind();
        dr.Close();
        conn.Close();
        conn.Dispose();
    }

Open in new window

0
Become a CompTIA Certified Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

ddayx10Commented:
Looks like Jinal and I have the same idea :)
0
ddayx10Commented:
Only thing is I would try not to use "FindControl" if I didn't have to...you pay a penalty for using that too often in a large project, and it should be avoided.
0
ddayx10Commented:
ha I'm looking at that and I thought akajt had posted that second posting (which jinal did) lol...I took first half of jinal's code and used it as a template for my post....for shame! Ah well give him the points if you award them...my bad.
0
jinalCommented:
Hello akajt,

Can you please look at my comment with ID:24819654 ? This is the same as  accepted solution.

You can contact moderator to chnage point if you wish.

Thanks.




0
akajtAuthor Commented:
Hello jinal,

The two responses are similar, however, I used the solution from ddayx10 because it didn't use the FindControl.  I have no problem with changing the assigned points.

Thanks!
0
jinalCommented:
You can contact moderator by request attention in question section on this page.

You can see that even other person agree that he did use my part of code for his comment.

Thanks and waiting for your response.
0
akajtAuthor Commented:
When I click on 'Request Attention' I receive the message:

This question has already been reported and may not be reported again so soon.
An Advisor will attend to the question shortly.

Apparently, someone else has an issue with the points that I assigned.  When I am contacted by the moderator, I will split the points.  I apologize if assigning the points to ddayx10 caused you to feel slighted.  This was not my intent.  I just found his code easier to follow.
0
ddayx10Commented:
I did feel bad about that jinal. It was an honest mistake. It doesn't just happen to you though....

happened to me here:
http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_24559094.html

I just go by the posting in the FAQ that states:
"If the question has been closed by the Asker, and he has awarded the points to another Expert, you can click the Request Attention button, but unless there is an obviously serious error, the Moderators will tend to accept the decision of the Asker; after all, she/he knows what worked for her/him."

I will say that...
a) although our code was similar I did not copy 1 line from your code behind (even though we took the same approach to the loop, anyone who knows what they are doing would take that approach)
b) the user did end up using my code as opposed to yours
c) I apologized right after I saw my mistake, and still think you deserve the points, but maybe not all since you used FindControl in such a way that was completely unnecessary. I should get like 1 point for quality control  :)
0
jinalCommented:
Hello ddayx10,
It is really a nice that you explain your point . I also agree that points should split between us.
Thanks.
0
ddayx10Commented:
Yes...

Jinal 499pt
Dday 1pt

LOL...you really did get there first pal points are not important in this context.
0
akajtAuthor Commented:
Although I did use the code from ddayx10, he wishes to have the points assigned to jinal.  Thanks to you both.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.