473,763 Members | 9,275 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Cannot Bind Check Box in DataGrid

I have the following code in my code behind page:

using System;
using System.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Sess ionState;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.H tmlControls;
using System.Data.Sql Client;

namespace CheckBoxTest
{
/// <summary>
/// Summary description for WebForm1.
public class WebForm1 : System.Web.UI.P age
{
protected System.Web.UI.W ebControls.Data Grid MyDataGrid;
SqlConnection myConnection;
private void Page_Load(objec t sender, System.EventArg s e)
{
myConnection = new SqlConnection

("Server=localh ost;uid=sa;pwd= preview;databas e=pubs");

if(!IsPostBack)
BindGrid();
}

private void MyDataGrid_Item DataBound(objec t sender,
System.Web.UI.W ebControls.Data GridItemEventAr gs e)
{
CheckBox cb = e.Item.FindCont rol("contract") as CheckBox;

if(cb != null)
{
if(DataBinder.E val(e.Item.Data Item,
"contract")!=DB Null.Value)
{
if(Convert.ToBo olean(DataBinde r.Eval(e.Item.D ataItem,
"contract") ) )
cb.Checked = true;
else
cb.Checked = false;
}
}
}

public void BindGrid()
{
SqlDataAdapter dAdapter = new SqlDataAdapter ("SELECT *
FROM authors ",
myConnection);
DataSet dSet= new DataSet();
dAdapter.Fill(d Set, "authors");

MyDataGrid.Data Source =
dSet.Tables["authors"].DefaultView;
MyDataGrid.Data Bind();
}

#region Web Form Designer generated code
override protected void OnInit(EventArg s e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form
Designer.
//
InitializeCompo nent();
base.OnInit(e);

}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent()
{
this.MyDataGrid .ItemDataBound += new
System.Web.UI.W ebControls.Data GridItemEventHa ndler
(this.MyDataGri d_ItemDataBound );

this.Load += new System.EventHan dler(this.Page_ Load);

}
#endregion
}
}

The problem I'm having is that the checkbox is not properly reflecting
the state of the underlying data field, which, in this case, is an SQL
2000 bit type. All of the checkboxes appear unchecked. (I want the
check box to appear checked if the underlying data field contains a "1"
and unchecked if it contains a "0".)

I added the event handler for the ItemDataBound event to
InitializeCompo nent, since that's where it seemed to make the most
sense.

Am I missing something *really* obviously wrong here?

Thanks!!!

Nov 19 '05 #1
4 2645
Try following in MyDataGrid_Item DataBound

if(e.Item.Itemt ype == ListItemType.It em || e.Item.ItemType ==
ListItemType.Al ternatingItem)
{
CheckBox cb = (CheckBox)e.Ite m.FindControl(" contract");
DataRowView drv = (DataRowView)e. Item.DataItem;
if(cb != null && !drv.Row.IsNull ("contract") )
{
cb.Checked = (bool)drv["contract"];

}
}
HTH

Elton Wang
"Nu2ASP.NET " wrote:
I have the following code in my code behind page:

using System;
using System.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Sess ionState;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.H tmlControls;
using System.Data.Sql Client;

namespace CheckBoxTest
{
/// <summary>
/// Summary description for WebForm1.
public class WebForm1 : System.Web.UI.P age
{
protected System.Web.UI.W ebControls.Data Grid MyDataGrid;
SqlConnection myConnection;
private void Page_Load(objec t sender, System.EventArg s e)
{
myConnection = new SqlConnection

("Server=localh ost;uid=sa;pwd= preview;databas e=pubs");

if(!IsPostBack)
BindGrid();
}

private void MyDataGrid_Item DataBound(objec t sender,
System.Web.UI.W ebControls.Data GridItemEventAr gs e)
{
CheckBox cb = e.Item.FindCont rol("contract") as CheckBox;

if(cb != null)
{
if(DataBinder.E val(e.Item.Data Item,
"contract")!=DB Null.Value)
{
if(Convert.ToBo olean(DataBinde r.Eval(e.Item.D ataItem,
"contract") ) )
cb.Checked = true;
else
cb.Checked = false;
}
}
}

public void BindGrid()
{
SqlDataAdapter dAdapter = new SqlDataAdapter ("SELECT *
FROM authors ",
myConnection);
DataSet dSet= new DataSet();
dAdapter.Fill(d Set, "authors");

MyDataGrid.Data Source =
dSet.Tables["authors"].DefaultView;
MyDataGrid.Data Bind();
}

#region Web Form Designer generated code
override protected void OnInit(EventArg s e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form
Designer.
//
InitializeCompo nent();
base.OnInit(e);

}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent()
{
this.MyDataGrid .ItemDataBound += new
System.Web.UI.W ebControls.Data GridItemEventHa ndler
(this.MyDataGri d_ItemDataBound );

this.Load += new System.EventHan dler(this.Page_ Load);

}
#endregion
}
}

The problem I'm having is that the checkbox is not properly reflecting
the state of the underlying data field, which, in this case, is an SQL
2000 bit type. All of the checkboxes appear unchecked. (I want the
check box to appear checked if the underlying data field contains a "1"
and unchecked if it contains a "0".)

I added the event handler for the ItemDataBound event to
InitializeCompo nent, since that's where it seemed to make the most
sense.

Am I missing something *really* obviously wrong here?

Thanks!!!

Nov 19 '05 #2
Nu3Asp.NET try looking through this sample at:-
http://www.dotnetjohn.com/articles.aspx?articleid=76
It should help
Patrick
"Nu2ASP.NET " <ms************ *@yahoo.com> wrote in message
news:11******** **************@ o13g2000cwo.goo glegroups.com.. .
I have the following code in my code behind page:

using System;
using System.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Sess ionState;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.H tmlControls;
using System.Data.Sql Client;

namespace CheckBoxTest
{
/// <summary>
/// Summary description for WebForm1.
public class WebForm1 : System.Web.UI.P age
{
protected System.Web.UI.W ebControls.Data Grid MyDataGrid;
SqlConnection myConnection;
private void Page_Load(objec t sender, System.EventArg s e)
{
myConnection = new SqlConnection

("Server=localh ost;uid=sa;pwd= preview;databas e=pubs");

if(!IsPostBack)
BindGrid();
}

private void MyDataGrid_Item DataBound(objec t sender,
System.Web.UI.W ebControls.Data GridItemEventAr gs e)
{
CheckBox cb = e.Item.FindCont rol("contract") as CheckBox;

if(cb != null)
{
if(DataBinder.E val(e.Item.Data Item,
"contract")!=DB Null.Value)
{
if(Convert.ToBo olean(DataBinde r.Eval(e.Item.D ataItem,
"contract") ) )
cb.Checked = true;
else
cb.Checked = false;
}
}
}

public void BindGrid()
{
SqlDataAdapter dAdapter = new SqlDataAdapter ("SELECT *
FROM authors ",
myConnection);
DataSet dSet= new DataSet();
dAdapter.Fill(d Set, "authors");

MyDataGrid.Data Source =
dSet.Tables["authors"].DefaultView;
MyDataGrid.Data Bind();
}

#region Web Form Designer generated code
override protected void OnInit(EventArg s e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form
Designer.
//
InitializeCompo nent();
base.OnInit(e);

}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent()
{
this.MyDataGrid .ItemDataBound += new
System.Web.UI.W ebControls.Data GridItemEventHa ndler
(this.MyDataGri d_ItemDataBound );

this.Load += new System.EventHan dler(this.Page_ Load);

}
#endregion
}
}

The problem I'm having is that the checkbox is not properly reflecting
the state of the underlying data field, which, in this case, is an SQL
2000 bit type. All of the checkboxes appear unchecked. (I want the
check box to appear checked if the underlying data field contains a "1"
and unchecked if it contains a "0".)

I added the event handler for the ItemDataBound event to
InitializeCompo nent, since that's where it seemed to make the most
sense.

Am I missing something *really* obviously wrong here?

Thanks!!!

Nov 19 '05 #3
Thank you everyone!!!

I have since resolved the issue, but I couldn't have done it without
your help and suggestions.

I really appreciate your input!

Nov 20 '05 #4
Thank You!

I solved the issue, and now have everthing binding as it should.

Here's my solution (in case anyone is curious):

<%@ Page language="c#" Codebehind="Web Form1.aspx.cs"
AutoEventWireup ="false" Inherits="Check BoxTest.WebForm 1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1 </title>
<meta content="Micros oft Visual Studio .NET 7.1"
name="GENERATOR ">
<meta content="C#" name="CODE_LANG UAGE">
<meta content="JavaSc ript" name="vs_defaul tClientScript">
<meta content="http://schemas.microso ft.com/intellisense/ie5"
name="vs_target Schema">
</HEAD>
<body MS_POSITIONING= "GridLayout ">
<form id="Form1" method="post" runat="server">
<ASP:DATAGRID id="MyDataGrid " runat="server"
AutoGenerateCol umns="false" HeaderStyle-
BackColor="#aaa add" Font-Size="8pt" Font-Name="Verdana"
CellSpacing="0" CellPadding="3" ShowFooter="fal se"
BorderColor="bl ack" BackColor="#ccc cff"
Width="800" OnItemDataBound ="MyDataGrid_It emDataBound">
<Columns>
<asp:BoundColum n HeaderText="au_ id" DataField="au_i d"/>
<asp:BoundColum n HeaderText="au_ lname"
DataField="au_l name" />
<asp:TemplateCo lumn HeaderText="au_ fname">
<ItemTemplate >
<asp:Label id="au_fname" Text='<%# DataBinder.Eval
(Container.Data Item, "au_fname") %>'
runat="server" />
</ItemTemplate>
</asp:TemplateCol umn>
<asp:BoundColum n HeaderText="cit y" DataField="city " />
<asp:TemplateCo lumn HeaderText="con tract">
<HeaderTemplate >
<input type="checkbox" id="checkAll" runat="server">
Contracts
</HeaderTemplate>
<ItemTemplate >
<asp:CheckBox id="contract" AutoPostBack=Tr ue
runat="server"> </asp:CheckBox>
</ItemTemplate>
</asp:TemplateCol umn>
</Columns>
</ASP:DATAGRID></form>
</body>
</HTML>

Code behind:
using System;
using System.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Sess ionState;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.H tmlControls;
using System.Data.Sql Client;

namespace CheckBoxTest
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>

public class WebForm1 : System.Web.UI.P age
{
protected System.Web.UI.W ebControls.Data Grid MyDataGrid;
SqlConnection myConnection;

private void Page_Load(objec t sender, System.EventArg s e)
{
myConnection = new SqlConnection

("Server=localh ost;uid=sa;pwd= preview;databas e=pubs");
if(!IsPostBack)
BindGrid();
}

public void MyDataGrid_Item DataBound(objec t sender,
System.Web.UI.W ebControls.Data GridItemEventAr gs e)
{
if(e.Item.ItemT ype == ListItemType.It em || e.Item.ItemType ==
ListItemType.Al ternatingItem)
{
CheckBox cb = e.Item.FindCont rol("contract") as CheckBox;
DataRowView drv = (DataRowView)e. Item.DataItem;

if(cb != null && !drv.Row.IsNull ("contract") )
{
cb.Checked = (bool)drv["contract"];
}
}

}
public void BindGrid()
{
SqlDataAdapter dAdapter = new SqlDataAdapter ("SELECT * FROM
authors ", myConnection);
DataSet dSet= new DataSet();
dAdapter.Fill(d Set, "authors");
MyDataGrid.Data Source = dSet.Tables["authors"].DefaultView;
MyDataGrid.Data Bind();
}
#region Web Form Designer generated code

override protected void OnInit(EventArg s e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form
// Designer.
//

InitializeCompo nent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>

private void InitializeCompo nent()
{
this.MyDataGrid .ItemDataBound += new
System.Web.UI.W ebControls.Data GridItemEventHa ndler
(this.MyDataGri d_ItemDataBound );
this.Load += new System.EventHan dler(this.Page_ Load);
}

#endregion
}

}

Thanks again to everyone for their help and suggestions. You were all a
great help.

--
Sent via .NET Newsgroups
http://www.dotnetnewsgroups.com
Nov 20 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
4090
by: Greg Linwood | last post by:
I am wondering what the best approach to binding XML data to an asp:Table from the Page_Load event in a code behind module? I'm using VB.Net and initially approached this by adding a table to the web page from the VS2003 ASP page designer, extracting an XML document from SQL Server during Page_Load, then adding asp:TableRows & asp:TableCells one at a time / loading the corresponding xml values a cell at a time. Is there a better (less...
1
8349
by: MS Newsgroups | last post by:
Hi, I have managed to create a Datagrid with a template column with checkboxes following Q306227. The dataset i have bound to the datagrid contains 1 column that allows NULL value and I would like to bind the checkbox to be checked if this value is anything else than DBNULL. I have used to designer to create the grid and dataset etc, and from what I understand I need to edit the databinding property of the checkbox in the template to...
6
5322
by: coleenholley | last post by:
I have a Class Module written in VB that calls an RPC (written in COBOL) we have written code to read the data from the RPC, and we create a temporary datatable to store the data from the RPC. This works fine when we call the datatable and bind it to a data grid using datagridname.DataBind(), but I have an ASP table, with calculations using tbl_name.row(1).cells(1) and the result of the calculation is put in a specific row and cell. I have...
3
2327
by: AFN | last post by:
I need to manually create the data to be shown in a datagrid (or some data table object). Should I create an array and bind the array to the datagrid OR should I create a temporary dataset and bind that to the datagrid? I have never done either (usually I get a recordset from a stored procedure and bind results directly). I also don't know which is faster. Whichever you suggest, can you give a couple lines of sample code? Thank...
3
10929
by: Joel Daniels | last post by:
Hello, I am trying to determine the proper way to access the underlying data row for a Repeater item in the ItemCommand event. In the page load event, I bind the Repeater data source to a SqlDataReader. I check for !IsPostBack so the data binding only happens the first time. In the ItemCommand event, e.Item.DataItem is unassigned. Any suggestions? Thanks!
1
4237
by: sianan | last post by:
I tried to use the following example, to add a checkbox column to a DataGrid in an ASP.NET application: http://www.codeproject.com/aspnet/datagridcheckbox.asp For some reason, I simply CAN'T get the example to work. I created the following two classes, provided with the example: *-*-**-*-*-*-*-*-*-*-*-*-**-*-*-*-*-CheckBoxColumn Class:-*-*-*-*-*-*-*-*-*-*-**-*-*-*-*-**-*-*-*
1
2950
by: Doug D via .NET 247 | last post by:
I really really need some insight on this problem I am trying to bind a strongly typed collection object to a datagrid. I already Inherited CollectionBase, but .NET says that it cannot find my property name, when I try to bind it to the grid.. now, here is where it gets tricky. Do I NEED to Implement IBindingList, on my collection object, since my object that I am adding to the collection inherits from a another class? here is my...
17
2770
by: A_PK | last post by:
I have problem databinding the DataGrid with DataView/DataSet after the filter... I create the following proceudre in order for user to filter as many as they want, but the following code is only allow user to filter the first time, when they tried the second time, the speficied cast error message will prompt one.... I create a mydataset1 first, and the mydataset1 data source was getting from DataGrid.DataSource.
1
1277
by: serge calderara | last post by:
Dear all, I have a datagrid which is bind to a databse table. One field of that table contains a filename. What I ma trying to do is to display the content of a cell to be an icon when the database field is not empty. In addition a direct link to the file will be done. Follow is my Datagrid structure for that column:
0
10002
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9938
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8822
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7368
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6643
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5270
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5406
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3917
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3528
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.