?
Solved

Gridview Boundfield and checkbox

Posted on 2009-07-09
15
Medium Priority
?
2,227 Views
Last Modified: 2013-11-26
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.
0
Comment
Question by:akajt
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 4
  • 3
15 Comments
 
LVL 20

Assisted Solution

by:ddayx10
ddayx10 earned 400 total points
ID: 24819514
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
 
LVL 15

Accepted Solution

by:
jinal earned 1600 total points
ID: 24819654
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
 
LVL 20

Expert Comment

by:ddayx10
ID: 24819941
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
Video: Liquid Web Managed WordPress Comparisons

If you run run a WordPress, you understand the potential headaches you may face when updating your plugins and themes. Do you choose to update on the fly and risk taking down your site; or do you set up a staging, keep it in sync with your live site and use that to test updates?

 
LVL 20

Expert Comment

by:ddayx10
ID: 24819944
Looks like Jinal and I have the same idea :)
0
 
LVL 20

Expert Comment

by:ddayx10
ID: 24819948
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
 
LVL 20

Expert Comment

by:ddayx10
ID: 24820529
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
 
LVL 15

Expert Comment

by:jinal
ID: 24842885
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
 

Author Comment

by:akajt
ID: 24843468
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
 
LVL 15

Expert Comment

by:jinal
ID: 24843510
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
 

Author Comment

by:akajt
ID: 24843592
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
 
LVL 20

Expert Comment

by:ddayx10
ID: 24846158
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
 
LVL 15

Expert Comment

by:jinal
ID: 24846214
Hello ddayx10,
It is really a nice that you explain your point . I also agree that points should split between us.
Thanks.
0
 
LVL 20

Expert Comment

by:ddayx10
ID: 24846660
Yes...

Jinal 499pt
Dday 1pt

LOL...you really did get there first pal points are not important in this context.
0
 

Author Closing Comment

by:akajt
ID: 31601889
Although I did use the code from ddayx10, he wishes to have the points assigned to jinal.  Thanks to you both.
0

Featured Post

NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Using Quotation Marks in PHP This question (http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28217211.html) seems to come up a lot for developers who are new to PHP.  And it got me thinking, "How can we explain the rule…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This video teaches viewers how to create their own website using cPanel and Wordpress. Tutorial walks users through how to set up their own domain name from tools like Domain Registrar, Hosting Account, and Wordpress. More specifically, the order in…
Learn how to set-up custom confirmation messages to users who complete your Wufoo form. Include inputs from fields in your form, webpage redirects, and more with Wufoo’s confirmation options.
Suggested Courses

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question