Solved

Adding Databound Checkbox Controls to the GridView prorammatically

Posted on 2006-06-16
12
13,041 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
Are your AD admin tools letting you down?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

 

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

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

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

This article discusses the ASP.NET AJAX ModalPopupExtender control. In this article we will show how to use the ModalPopupExtender control, how to display/show/call the ASP.NET AJAX ModalPopupExtender control from javascript, how to show/display/cal…
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 …
In a recent question (https://www.experts-exchange.com/questions/28997919/Pagination-in-Adobe-Acrobat.html) here at Experts Exchange, a member asked how to add page numbers to a PDF file using Adobe Acrobat XI Pro. This short video Micro Tutorial sh…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…

777 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