Solved

Gridview Boundfield and checkbox

Posted on 2009-07-09
15
2,059 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
  • 7
  • 4
  • 3
15 Comments
 
LVL 20

Assisted Solution

by:ddayx10
ddayx10 earned 100 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 400 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
 
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
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 

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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

Introduction HyperText Transfer Protocol (http://www.ietf.org/rfc/rfc2616.txt) or "HTTP" is the underpinning of internet communication.  As a teacher of web development I have heard many questions, mostly from my younger students who have come to t…
Thoughout my experience working on eCommerce web applications I have seen applications succumbing to increased user demand and throughput. With increased loads the response times started to spike, which leads to user frustration and lost sales. I ha…
This video teaches users how to migrate an existing Wordpress website to a new domain.
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.

757 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now