Solved

Adding Databound Checkbox Controls to the GridView prorammatically

Posted on 2006-06-16
12
13,039 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Execute Stored Procedure for a set of values 5 45
LINQ - C# to VB convertion 12 48
Word Directory is not in the drop down list 4 26
SQL Exceptions 3 40
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…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This is used to tweak the memory usage for your computer, it is used for servers more so than workstations but just be careful editing registry settings as it may cause irreversible results. I hold no responsibility for anything you do to the regist…
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…

863 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