Solved

Adding Databound Checkbox Controls to the GridView prorammatically

Posted on 2006-06-16
12
13,031 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
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
 

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
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 

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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

Lots of people ask this question on how to extend the “MembershipProvider” to make use of custom authentication like using existing database or make use of some other way of authentication. Many blogs show you how to extend the membership provider c…
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

706 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

20 Experts available now in Live!

Get 1:1 Help Now