Solved

Adding Databound Checkbox Controls to the GridView prorammatically

Posted on 2006-06-16
12
13,043 Views
Last Modified: 2011-08-18
I need to add a checkbox to every row in a databound GridView. Of course there is a field in the database table that will deterimine whether the row's checkbox is selected or not. I would also need to update the database table should the checkbox be seleted or deselected. I know this can be done and that it can be done programmatically in the code behind class file but finding the right syntax has proven quite difficult. Any help would be appreciated.

Thanks!
0
Comment
Question by:HangTenDesign
[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
12 Comments
 
LVL 20

Expert Comment

by:REA_ANDREW
ID: 16920943
to be honest I am learning these eventargs for the GridView my self.  I have been able to programmatically add a new column to the grid view and also add checkboxes. up to now here is my code to do that

    protected void Page_Load(object sender, EventArgs e)
    {
        BoundField MyField = new BoundField();
        MyField.HeaderText = "HEADER";
        DataControlField MyControlField = (DataControlField)new BoundField();
        GridView1.Columns.Add(MyControlField);
    }
    protected void AddExtra(object sender, GridViewRowEventArgs e)
    {
        e.Row.Cells[3].Controls.Add(new CheckBox());
    }

also I add this attribute to the tag line

OnRowDataBound="AddExtra"
0
 
LVL 25

Expert Comment

by:nauman_ahmed
ID: 16921012
You will need to do that using TemplateColumn in the datagrid. To control the state of the checkbox you will bind the datagrid and process the code in Item_Created event:


ASPX
******

<TemplateColumn>
<ItemTemplate>
<asp:checkbox id=chk1 runat=server />
</ItemTemplate>
</TemplateColumn>

VB.NET
*******
private sub MyDataGrid_ItemCreate(src as object, e as DataGridItemEventArgs) Handles MyDataGrid.ItemCreated

if Convert.ToString(DataBinder.Eval(e.Item.DataItem,"BOOLEAN_COLUMN_NAME")) = "1" Then
  for each c as control in e.Item.Cells(CHECKBOX_COLUMN_INDEX).Controls
     if c.getype() = typeof(CheckBox) then
        c.checked = true
     end if
   Next
end if

End Sub

-Nauman.
0
 

Author Comment

by:HangTenDesign
ID: 16922087
Yes, this is great nauman_ahmed. However, there is definitely a way to programmatically create EVERY control and EVERY property of a control. So the question is, how do I create the ...

<TemplateColumn>
<ItemTemplate>
<asp:checkbox id=chk1 runat=server />
</ItemTemplate>
</TemplateColumn>

... programmatically along with the other columns I'm creating on the fly?
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:HangTenDesign
ID: 16922386
Ok this one worked:

in the page onload:

tf = new TemplateField();
tf.HeaderText = checklist_type_desc;
tf.ItemStyle.VerticalAlign = VerticalAlign.Top;
tf.ItemTemplate = new GridViewCheckBoxColumn();
ChecklistView.Columns.Add(tf);

This creates the DataBound template column on the fly with the other column I'm creating.

Other code included in the codebehind class for the defined GridViewCheckBoxColumn():

public class GridViewCheckBoxColumn : ITemplate
    {
        public GridViewCheckBoxColumn()
        {
            //Add constructor stuff here
        }

        public void InstantiateIn(Control container)
        {
            CheckBox cb = new CheckBox();
            cb.DataBinding += new EventHandler(this.BindChecklistColumn);
            container.Controls.Add(cb);
        }

        public void BindChecklistColumn(object sender, EventArgs e)
        {
            CheckBox cb = (CheckBox)sender;
            GridViewRow container = (GridViewRow)cb.NamingContainer;
            cb.ID = Convert.ToString(DataBinder.Eval(((GridViewRow)container).DataItem, "ITEM_ID"));

        }
    }

I re-purposed this code to work for me:
http://www.411asp.net/func/content-hot?id=5537710

I'm not there yet though. I need to be able to add an onClick event for each checkbox to handle whether it's checked or not.

0
 
LVL 25

Expert Comment

by:nauman_ahmed
ID: 16922530
Where you want to add onClick event?

-Nauman.
0
 

Author Comment

by:HangTenDesign
ID: 16922572
For each check box and I need to know which check box was clicked.
0
 
LVL 25

Expert Comment

by:nauman_ahmed
ID: 16922750
Are you talking about retaining the checkbox value or you want the page to postback when the checbox is clicked? If you want to retain the checkbox value while the paging occur, you can do it as mentioned in the following article:

Storing and Maintaining DataGrid CheckBox Values
http://www.developerfusion.co.uk/show/5258/3/

-Nauman.



0
 

Author Comment

by:HangTenDesign
ID: 16923291
Nope, not using pageing.

BUT.....so far I have everything working perfect!!! I am able to retain checkbox values on postback when I create the dynamic controls in the OnInit method. It didn't work in the  Page_Load. (http://aspnet.4guysfromrolla.com/articles/092904-1.aspx) I added the AutoPostBack to the dynamic checkbox and it's working like a charm. My last step I haven't solved yet. I still need to capture the checkbox values for each row for updating the database during the PostBack.
0
 

Author Comment

by:HangTenDesign
ID: 16934457
So far I am enumerating through the GridView rows (I think!!!!!) to capture the Row's DataIndex value BUT I am getting an error. Can anyone help me with this???

This is the code I have so far:

           for (int i = 0; i < ChecklistView.Rows.Count - 1; i++)
            {
                CheckBox cb = (CheckBox)ChecklistView.Rows[i].FindControl("ChecklistItem");

                if (cb.Checked)  //I keep getting an error on this line, see below
                {
                    Test.Text += ChecklistView.DataKeys[i].ToString() + "<br>";
                }

            }

The error I keep getting is:
System.NullReferenceException: Object reference not set to an instance of an object.
 
I know for a fact that every row has this checkbox.


0
 

Author Comment

by:HangTenDesign
ID: 16936477
Well, I solved it myself.

This is how I am iterating through the collection:

            foreach (GridViewRow gvr in ChecklistView.Rows)
            {
                CheckBox cb = (CheckBox)gvr.Cells[gvr.Cells.Count-1].Controls[0];
                if (cb.Checked)
                {
                    Test.Text += ChecklistView.DataKeys[gvr.RowIndex].Value.ToString() + "<br>";
                }
            }

The rest is a cake walk. Thanks for everyone's help.
0
 
LVL 1

Accepted Solution

by:
DarthMod earned 0 total points
ID: 17160201
PAQed with points refunded (500)

DarthMod
Community Support Moderator
0

Featured Post

Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Footer for each row on Gridview 2 41
asp.net open new page without popup blocker 8 39
ASP.NET MVC - Views 3 42
Google Maps with Webforms 1 29
I have developed many web applications with asp & asp.net and to add and use a dropdownlist was always a very simple task, but with the new asp.net, setting the value is a bit tricky and its not similar to the old traditional method. So in this a…
Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

733 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