Find answers for the most frequently asked questions
Why does the DataGrid web server control contents wrap when ItemStyle Wrap or HeaderStyle Wrap Property is set to False
The wrap functionality occurs for each cell and not for each row of the DataGrid. Therefore, if you disabled the wrap functionality for all of the DataGrid, text wrapping functionality is not disabled for every row or column.
To resolve this make sure that every column of the DataGrid has the ItemStyle Wrap property explicitly set to False as follows:
How to export data in Datagrid on a webform to Microsoft Excel
Two techniques for exporting the data in the DataGrid:
Using the Excel MIME Type (or Content Type)
With server-side code, you can bind the DataGrid to your data and have the data open in Excel on a client computer. To do this, set the ContentType to application/vnd.ms-excel. After the client receives the new stream, the data appears in Excel as if the content was opened as a new page in the Web browser.
Using Excel Automation
With client-side code, you can extract the HTML from the DataGrid and then Automate Excel to display the HTML in a new workbook. With Excel Automation, the data always appears outside the browser in an Excel application window. One advantage to Automation is that you can programmatically control Excel if you want to modify the workbook after the data is exported. However, because Excel is not marked as safe for scripting, your clients must apply security settings in the Web browser that allow Automation.
How do I use Validator controls while editing data in the DataGrid?
Yes, you can use the Asp.Net validation controls inside a Datagrid. You’ll need to use a TemplateColumn, and on the TextBoxes (or other controls) in your EditItemTemplate, be sure to give them an ID. Then specify that ID as the ControlToValidate for the validation control.
PrivateSub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
’ Put user code to initialize the page hereIfNot Page.IsPostBack Then’Populate the dataSet’Bind the dataGrid with the dataView
DataGrid1.DataSource = BindTheDataClass.Binddata().Tables(0).DefaultView
DataGrid1.DataBind()
EndIfEndSub’Page_LoadProtectedSub ItemDB(ByVal sender AsObject, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)
Dim dv As DataView = CType(DataGrid1.DataSource, DataView)
Dim drv As DataRowView = CType(e.Item.DataItem, DataRowView)
If dv.Table.Rows.Count = 0Then’By default the Datagrid Header is shown in case there is no Data Available’So in case of No Data found ’Check the ListItemType.HeaderIf e.Item.ItemType = ListItemType.Header ThenDim i AsInteger = e.Item.Cells.Count
’Assign 'No Search result Found' in one of the cells of DataGrid
e.Item.Cells(0).Text = 'No Search Results Found'’Remove Rest of the empty cells from DatagridDim j AsIntegerFor j = i - 1To1Step -1
e.Item.Cells.RemoveAt(j)
NextEndIfEndIfEndSub’ItemDB
C#
privatevoidPage_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page hereif (!Page.IsPostBack )
{
//Fill DataSet//Bind the DataGrid with the DataView
DataGrid1.DataSource =ds.Tables[0].DefaultView ;
DataGrid1.DataBind ();
}
}
protectedvoidItemDB(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
DataView dv =(DataView)DataGrid1.DataSource ;
DataRowView drv = (DataRowView)e.Item.DataItem ;
if (dv.Table.Rows.Count == 0 )
{
//By default the Datagrid Header is shown in case there is no Data Available//So in case of No Data found //Check the ListItemType.Headerif ((e.Item.ItemType == ListItemType.Header))
{
int i= e.Item.Cells.Count;
//Assign 'No Search result Found' in one of the cells of DataGrid
e.Item.Cells [0].Text = 'No Search Results Found';
//Remove Rest of the empty cells from Datagridfor (int j=i-1;j>0;j--)
{
e.Item.Cells.RemoveAt(j);
}
}
}
}
Why do I get ‘Could not lock file’ and ‘cannot open file’ exceptions when bound to a mdb file?
You could get this error for the following reasons:
When you create a project afresh, add a new OleDbDataAdapter to the form and link to the mdb file, the connection object created in the process will keep an open connection to the mdb file which is what will cause the above ‘Could not lock file’ exception during runtime. To workaround this, go to ‘Server Explorer’ in your IDE, right click on the corresponding ‘Connection entry’ and select Close Connection. This should fix the problem.
The ‘cannot open file’ exception could then occur if you have not provided enough permissions on the mdb file to allow the .net runtime to lock it. To ensure enough permissions, open it’s properties, select the Security tab and add a ‘Everyone’ account granting ‘Full Control’ to it. This should let the .net runtime lock the file.
PrivateSub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
’Populate the DataGridEndSubprotectedSub ItemDB(ByVal sender AsObject, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)
If e.Item.ItemType = ListItemType.Header Then
e.Item.Cells(0).Text = 'Employee ID'
e.Item.Cells(1).Text = 'First Name'
e.Item.Cells(2).Text = 'Last Name'EndIfEndSub
Dim cn As SqlConnection
Dim da As SqlDataAdapter
Dim ds As DataSet
PrivateSub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
’ Put user code to initialize the page here
cn = New SqlConnection('Server=localhost;uid=sa;pwd=;database=northwind')IfNot Page.IsPostBack Then
da = New SqlDataAdapter('SELECT orderid FROM orders', cn)
ds = New DataSet
da.Fill(ds, 'Orders')
DataGrid1.DataSource = ds
DataGrid1.DataBind()
EndIfEndSub’Page_LoadProtectedSub ItemDB(ByVal sender AsObject, ByVal e As DataGridItemEventArgs)
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem ThenDim dgDetails AsNew DataGrid
Dim orderid AsInteger = CInt(CType(e.Item.DataItem, DataRowView)('OrderID'))
dgDetails.DataSource = GetOrderDetails(orderid)
dgDetails.DataBind()
e.Item.Cells(1).Controls.Add(dgDetails)
EndIfEndSub’ItemDBFunction GetOrderDetails(ByVal id AsInteger) As DataSet
da = New SqlDataAdapter('SELECT * FROM [Order Details] where orderid=' + id.ToString, cn)
ds = New DataSet
da.Fill(ds, 'OrderDetails')Return ds
EndFunction’GetOrderDetails
C#
SqlConnection cn;
SqlDataAdapter da;
DataSet ds;
privatevoidPage_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
cn= new SqlConnection ('Server=localhost;uid=sa;pwd=;database=northwind');
if (!Page.IsPostBack)
{
da= new SqlDataAdapter ('SELECT orderid FROM orders ', cn);
ds= new DataSet ();
da.Fill (ds, 'Orders');
DataGrid1.DataSource = ds;
DataGrid1.DataBind ();
}
}
protectedvoidItemDB(Object sender,DataGridItemEventArgs e )
{
if ((e.Item.ItemType == ListItemType.Item)||(e.Item.ItemType == ListItemType.AlternatingItem ))
{
DataGrid dgDetails = new DataGrid();
int orderid =(int) ((DataRowView)e.Item.DataItem)['OrderID'] ;
dgDetails.DataSource = GetOrderDetails(orderid );
dgDetails.DataBind();
e.Item.Cells[1].Controls.Add(dgDetails);
}
}
DataSet GetOrderDetails(int id )
{
da= new SqlDataAdapter ('SELECT * FROM [Order Details] where orderid= ' + id, cn);
ds= new DataSet ();
da.Fill (ds, 'OrderDetails');
return ds;
}
Dim cn As SqlConnection
Dim da As SqlDataAdapter
Dim cmd As SqlCommand
Dim strsql AsStringDim ds As DataSet
PrivateSub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
’Put user code to initialize the page here
cn = New SqlConnection('Server=localhost;uid=sa;pwd=;database=northwind;')IfNot Page.IsPostBack Then
BindData()
EndIfEndSubSub BindData()
DataGrid1.DataSource = GetData('Select * from Region')
DataGrid1.DataBind()
EndSubFunction GetData(ByVal strSql AsString) As DataSet
da = New SqlDataAdapter(strSql, cn)
ds = New DataSet()
da.Fill(ds)
Return ds
EndFunctionProtectedSub ItemCommand(ByVal source AsObject, _
ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs)
If e.CommandName = 'Edit' Then’Fill the Textboxes with relevant data
FillTheData(e.Item.Cells(1).Text, e.Item.Cells(2).Text)
EndIfEndSubSub FillTheData(ByVal RegionID AsString, ByVal RegionDescription AsString)
txtRegionID.Text = RegionID
txtRegionDescription.Text = RegionDescription
EndSubPrivateSub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
Try
strsql = 'Update Region set RegionDescription=@RegionDescription where RegionId=@RegionId'
cmd = New SqlCommand(strsql, cn)
cmd.Parameters.Add(New SqlParameter('@RegionId', SqlDbType.Int))
cmd.Parameters.Add(New SqlParameter('@RegionDescription', SqlDbType.NVarChar, 40))
cmd.Parameters('@RegionId').Value = Convert.ToInt32(txtRegionID.Text)
cmd.Parameters('@RegionDescription').Value = txtRegionDescription.Text
cn.Open()
cmd.ExecuteNonQuery()
BindData()
lblMessage.Text = 'Updated Successfully'Catch ex As Exception
lblMessage.Text = ex.Message
lblMessage.ForeColor = Color.Red
Finally
cn.Close()
EndTryEndSub
C#
SqlConnection cn;
SqlDataAdapter da ;
SqlCommand cmd ;
string strsql ;
DataSet ds ;
privatevoidPage_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
cn = new SqlConnection('Server=localhost;uid=sa;pwd=;database=northwind;');
if(!Page.IsPostBack)
{
//Code to Bind the data to the Datagrid
BindData();
}
}
voidBindData()
{
DataGrid1.DataSource = GetData('Select * from Region');
DataGrid1.DataBind();
}
DataSet GetData(string strSql)
{
da = new SqlDataAdapter(strSql, cn);
ds = new DataSet();
da.Fill(ds);
return ds;
}
protectedvoidItemCommand(Object source,System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if (e.CommandName == 'Edit')
{
//’Fill the Textboxes with relevant data
FillTheData(e.Item.Cells[1].Text, e.Item.Cells[2].Text);
lblMessage.Text='';
}
}
voidFillTheData(string RegionID,string RegionDescription)
{
txtRegionID.Text = RegionID;
txtRegionDescription.Text = RegionDescription;
}
privatevoidbtnUpdate_Click(object sender, System.EventArgs e)
{
try
{
strsql = 'Update Region set RegionDescription=@RegionDescription where RegionId=@RegionId';
cmd = new SqlCommand(strsql, cn);
cmd.Parameters.Add(new SqlParameter('@RegionId', SqlDbType.Int));
cmd.Parameters.Add(new SqlParameter('@RegionDescription', SqlDbType.NVarChar, 40));
cmd.Parameters['@RegionId'].Value = Convert.ToInt32(txtRegionID.Text);
cmd.Parameters['@RegionDescription'].Value = txtRegionDescription.Text;
cn.Open();
cmd.ExecuteNonQuery();
BindData();
lblMessage.Text = 'Updated Successfully';
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
lblMessage.ForeColor = Color.Red;
}
finally
{
cn.Close();
}
}
When I try to do an Update from my Datagrid, I keep getting the old/original values. Why?
This could happen if you are calling .DataBind everytime the Page is loaded
To avoid this call Databind only for the first request and not for subsequent postbacks.
I have set the ItemStyle and the AlternatingItemStyle tags for DataGrid control but they aren’t working correctly , why?
DataGrid generates an HTML Table, with TableRows and Cells. If you already have some display properties set for <td>,<TR>… make sure to check them in the Stylesheet. Whatever properties you set there will normally override whatever you add into your DataGrid’s Item styles.
protectedSub dgPreRender(ByVal sender AsObject, ByVal e As System.EventArgs)
Dim dgItem AsNew DataGridItem(0, 0, ListItemType.Header)
Dim tbCell AsNew TableCell
tbCell.ColumnSpan = 3’Set it to the colspan that you want
tbCell.Text = 'Category Information'
tbCell.Attributes.Add('style', 'text-align:center')
dgItem.Cells.Add(tbCell)
DataGrid1.Controls(0).Controls.AddAt(0, dgItem)
EndSub
C#
protectedvoiddgPreRender(object sender, System.EventArgs e )
{
DataGridItem dgItem = new DataGridItem (0, 0, ListItemType.Header);
TableCell tbCell = new TableCell();
tbCell.ColumnSpan = 3;// Set it to the colspan that you want
tbCell.Text = 'Category Information';
tbCell.Attributes.Add('style', 'text-align:center');
dgItem.Cells.Add(tbCell);
DataGrid1.Controls[0].Controls.AddAt(0, dgItem);
}
How to use the DataFormatString to format DataGrid data dynamically
In the ItemDataBound Event of DataGrid write following code.
VB.NET
Dim ds As DataSet = CType(DataGrid1.DataSource, DataSet)
Dim dv As DataView = ds.Tables(0).DefaultView
Dim dcCol As DataColumnCollection = dv.Table.Columns
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
e.Item.Cells(dcCol.IndexOf(dcCol('UnitPrice'))).Text = DataBinder.Eval(e.Item.DataItem, 'UnitPrice', '{0:c}')EndIf
Why do I get the error message ‘ CS1502: The best overloaded method match for ‘xxx(string)’ has some invalid arguments ‘ when I use Helper function in DataGrid
The function xxx() is expecting a string, but DataBinder.Eval() returns an object. So you must cast the result of DataBinder.Eval() to a string (or, in this case, just use .ToString()).
Why am I getting an ‘AllowCustomPaging must be true and VirtualItemCount must be set for a DataGrid with ID MyDataGrid when AllowPaging is set to true and the selected datasource does not implement ICollection’ Error?
You are probably trying to implement paging in a DataGrid while binding the DataGrid with a DataReader.
To fix this, instead of using a DataReader use a DataSet
How to open a new window with multiple parameters when clicked on a hyperlink in a column in a datagrid
The column should be defined as a TemplateColumn as follows and the NavigateUrl for that hyperlink can be set as follows to open a new window with parameters varying based on the row in which the hyperlink is present.
Dim count AsIntegerprotectedfunction getCount() AsInteger
count = count + 1Return count
EndFunctionPrivateSub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
’Populate the Datagrid populating data from the database’..... EndSub
C#
int count =0;
protectedintgetCount()
{
count = count + 1;
return count;
}
privatevoidPage_Load(object sender, System.EventArgs e)
{
//Populate the Datagrid populating data from the database//....
}
Step 1: Create linkbuttons to display the alphabets at the footer of the datagrid
Step 2: Add this buttons in the ItemCreated event . Use the CommandName and CommandArgument properties of the LinkButton to identify them
Step 3: To handle the Paging , In the ItemCommand Event respond to action based on the CommandName and CommandArgument of LinkButton that caused event to be raised.
PrivateSub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
’ Put user code to initialize the page hereIfNot Page.IsPostBack Then
BindGrid('')EndIfEndSubSub BindGrid(ByVal stralpha AsString)
Dim cn As SqlConnection
Dim da As SqlDataAdapter
Dim ds As DataSet
cn = New SqlConnection('Server=localhost;uid=sa;pwd=;database=pubs')Dim strsql AsString = 'Select * from authors 'If stralpha = '' Then
strsql = strsql
Else
strsql = strsql + ' where au_lname like’' + stralpha + '%’'EndIf
da = New SqlDataAdapter(strsql, cn)
ds = New DataSet
da.Fill(ds, 'Product')If (ds.Tables(0).Rows.Count = 0) Then
Response.Write('No Data Found')
DataGrid1.DataSource = Nothing
DataGrid1.DataBind()
Else
DataGrid1.DataSource = ds
DataGrid1.DataBind()
EndIfEndSubProtectedSub ItemCreated(ByVal sender AsObject, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)
If e.Item.ItemType = ListItemType.Footer Then
e.Item.Cells.Clear()
Dim tc As TableCell = New TableCell
tc.ColumnSpan = 2
e.Item.Cells.Add(tc)
Dim lc As LiteralControl
Dim lb As LinkButton
Dim i AsIntegerFor i = 65To65 + 25
lc = New LiteralControl
lb = New LinkButton
lc.Text = ' '
lb.Text = Chr(i)
lb.CommandName = 'alpha'
lb.CommandArgument = Chr(i)
tc.Controls.Add(lb)
tc.Controls.Add(lc)
NextEndIfEndSubProtectedSub ItemCommand(ByVal source AsObject, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs)
If (e.CommandName = 'alpha') Then
BindGrid(e.CommandArgument.ToString())
EndIfEndSub
C#
privatevoidPage_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page hereif (!Page.IsPostBack )
{
BindGrid('');
}
}
voidBindGrid(string stralpha)
{
SqlConnection cn;
SqlDataAdapter da;
DataSet ds;
cn = new SqlConnection ('Server=localhost;uid=sa;pwd=;database=pubs');
string strsql ='Select * from authors ';
if (stralpha=='')
{
strsql = strsql ;
}
else
{
strsql = strsql + ' where au_lname like’' + stralpha + '%’';
}
da= new SqlDataAdapter (strsql,cn);
ds= new DataSet ();
da.Fill (ds, 'Product');
if (ds.Tables [0].Rows.Count ==0)
{
Response.Write ('No Data Found');
DataGrid1.DataSource=null;
DataGrid1.DataBind ();
}
else
{
DataGrid1.DataSource =ds;
DataGrid1.DataBind ();
}
}
protectedvoidItemCreated(Object sender , System.Web.UI.WebControls.DataGridItemEventArgs e )
{
if (e.Item.ItemType == ListItemType.Footer)
{
e.Item.Cells.Clear();
TableCell tc = new TableCell();
tc.ColumnSpan = 2;
e.Item.Cells.Add(tc);
LiteralControl lc;
LinkButton lb;
string s='' ;
for (char c=’A’ ; c<= ’Z’ ; )
{
lc = newLiteralControl ();
lb = new LinkButton ();
s = c.ToString() ;
lc.Text =' ';
lb.CommandName ='alpha';
lb.CommandArgument= s;
lb.Text=s;
c =(char)((int)c +1) ;
tc.Controls.Add(lb);
tc.Controls.Add(lc);
}
}
}
protectedvoidItemCommand(Object source , System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if (e.CommandName == 'alpha' )
{
BindGrid(e.CommandArgument.ToString ());
}
}
I am binding the DataGrid to a datasource at runtime. After binding I want to populate a listbox with the column headers from the datagrid. How can I reference the column headertext for each column in the datagrid and then add them to my listbox
In the ItemDataBound Event write following code
VB.NET
Dim i AsInteger = 0If e.Item.ItemType = ListItemType.Header ThenFor i = 0To e.Item.Cells.Count -1Me.ListBox1.Items.Add(e.Item.Cells(i).Text)
NextEndIf
C#
if (e.Item.ItemType== ListItemType.Header)
{
for(int i = 0; i <= e.Item.Cells.Count-1 ; i++)
{
this.ListBox1.Items.Add(new ListItem(e.Item.Cells[i].Text));
}
}
PrivateSub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
’Bind the Datagrid with dataSetEndSubPrivateSub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Response.Write('You have selected :' & txtFname.Text)EndSub
C#
privatevoidPage_Load(object sender, System.EventArgs e)
{
//Bind the datagrid to dataset
}
privatevoidButton1_Click(object sender, System.EventArgs e)
{
Response.Write('You have selected :' + txtFname.Text);
}
Protected SQLStmt AsString = 'Select * from Products 'Dim myconnection As SqlConnection
Dim myda As SqlDataAdapter
Dim ds As DataSet
Dim strConn AsStringPrivateSub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
’Put user code to initialize the page here
binddata()
EndSubSub binddata()
strConn = 'Server=localhost;uid=sa;password=;database=northwind;'
myconnection = New SqlConnection(strConn)
myda = New SqlDataAdapter(SQLStmt, myconnection)
ds = New DataSet
myda.Fill(ds, 'AllTables')
DataGrid1.DataSource = ds
DataGrid1.DataBind()
EndSubProtectedSub SortDataGrid(ByVal source AsObject, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs)
If ViewState('SortOrder') Is Nothing Then
ViewState('SortOrder') = ' ASC'ElseIf ViewState('SortOrder') = ' ASC' Then
ViewState('SortOrder') = ' DESC'Else
ViewState('SortOrder') = ' ASC'EndIf
SQLStmt = SQLStmt & ' ORDER BY ' & e.SortExpression & ' ' & ViewState('SortOrder')
binddata()
EndSub
C#
SqlConnection myconnection ;
SqlDataAdapter myda ;
DataSet ds ;
String strConn ;
string SQLStmt= 'Select * from Products ';
privatevoidPage_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
binddata();
}
voidbinddata()
{
strConn = 'Server=localhost;uid=sa;password=;database=northwind;';
myconnection =new SqlConnection(strConn);
myda = new SqlDataAdapter(SQLStmt, myconnection);
ds = new DataSet();
myda.Fill(ds, 'AllTables');
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
}
protectedvoidSortDataGrid(object source , System.Web.UI.WebControls.DataGridSortCommandEventArgs e )
{
if (ViewState['SortOrder'] ==null)
{
ViewState['SortOrder'] = ' ASC';
}
elseif (ViewState['SortOrder'].ToString () == ' ASC' )
{
ViewState['SortOrder'] = ' DESC';
}
else
{
ViewState['SortOrder'] = ' ASC';
}
SQLStmt = SQLStmt + ' ORDER BY ' + e.SortExpression.ToString () + ' ' + ViewState['SortOrder'];
binddata();
}
PrivateSub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
’Put user code to initialize the page hereIfNot Page.IsPostBack Then’Bind the dataGrid to DataViewEndIfEndSubProtectedSub ItemDB(ByVal sender AsObject, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)
Dim dv As DataView = DataGrid1.DataSource
Dim dcCol As DataColumn
Dim dc As DataColumnCollection = dv.Table.Columns
Dim strID AsStringForEach dcCol In dv.Table.Columns
If e.Item.ItemType = ListItemType.AlternatingItem Or _
e.Item.ItemType = ListItemType.Item Then
strID = DataGrid1.DataKeys(e.Item.ItemIndex)
e.Item.Cells(dc.IndexOf(dc(dcCol.ColumnName))).Attributes.Add('style', 'cursor:hand')
e.Item.Cells(dc.IndexOf(dc(dcCol.ColumnName))).Attributes.Add('onclick', _'javascript:window.open(’details.aspx?id=' & strID & '’,' _
& '’MyPage’,’height=300,width=300’)')EndIfNextEndSub
C#
privatevoidPage_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page hereif(!Page.IsPostBack )
{
//Bind Datagrid to DataView
}
}
protectedvoidItemDB(object sender , System.Web.UI.WebControls.DataGridItemEventArgs e )
{
DataView dv = (DataView)DataGrid1.DataSource;
DataColumnCollection dc = dv.Table.Columns ;
string strID;
foreach (DataColumn dcCol in dv.Table.Columns)
{
if ((e.Item.ItemType == ListItemType.AlternatingItem )||(e.Item.ItemType == ListItemType.Item ))
{
strID = DataGrid1.DataKeys[e.Item.ItemIndex].ToString ();
e.Item.Cells[dc.IndexOf(dc[dcCol.ColumnName])].Attributes.Add('style', 'cursor:hand');
e.Item.Cells[dc.IndexOf(dc[dcCol.ColumnName])].Attributes.Add('onclick', 'javascript:window.open(’details.aspx?id=' + strID + '’,' + '’MyPage’,’height=300,width=300’)');
}
}
}
Dim UnitPrice AsDoublePrivateSub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
’Put user code to initialize the page here’Bind the Data to datagridEndSubProtectedSub UPTotal(ByVal _unitprice AsDouble)
UnitPrice += _unitprice
EndSub’UPTotalPublicSub ItemDB(ByVal sender AsObject, ByVal e As DataGridItemEventArgs)
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
UPTotal(Double.Parse(e.Item.Cells(1).Text.ToString))
ElseIf e.Item.ItemType = ListItemType.Footer Then
e.Item.Cells(0).Text = ' Total '
e.Item.Cells(1).Text = UnitPrice.ToString()
EndIfEndIfEndSub’ItemDB
C#
double UnitPrice;
privatevoidPage_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page hereif(!Page.IsPostBack )
{
//Bind the DataGrid
}
}
protectedvoidUPTotal(double_unitprice)
{
UnitPrice += _unitprice;
}
publicvoidItemDB(object sender, DataGridItemEventArgs e)
{
if ((e.Item.ItemType == ListItemType.Item) ||( e.Item.ItemType == ListItemType.AlternatingItem))
{
UPTotal(Double.Parse ( e.Item.Cells[1].Text ));
}
elseif (e.Item.ItemType ==ListItemType.Footer )
{
e.Item.Cells [0].Text =' Total ';
e.Item.Cells[1].Text =UnitPrice.ToString ();
}
}
’Fill the DataSet ds with data from databaseDim dc As DataColumn
dc = New DataColumn('Total', Type.GetType('System.Double'))
dc.Expression = 'UnitPrice * UnitsInStock'
ds.Tables(0).Columns.Add(dc)
DataGrid1.DataSource = ds
DataGrid1.DataBind()
C#
//Fill the DataSet ds with data from database
DataColumn dc ;
dc = new DataColumn('Total', Type.GetType('System.Double'));
dc.Expression = 'UnitPrice * UnitsInStock';
ds.Tables[0].Columns.Add(dc);
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
PrivateSub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
’Put user code to initialize the page hereIfNot IsPostBack Then’Populate the datagridEndIfEndSubprotectedSub chkChanged(ByVal sender AsObject, ByVal e As System.EventArgs)
Response.Write('CheckChanged Event')EndSub
C#
privatevoidPage_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page hereif (!Page.IsPostBack )
{
DataGrid1.DataSource =BindDataClass.BindData ();
DataGrid1.DataBind ();
}
}
protectedvoidchkChanged(object sender , System.EventArgs e )
{
Response.Write('CheckChanged Event');
}
ProtectedSub ItemCmd(source AsObject, e As System.Web.UI.WebControls.DataGridCommandEventArgs)
If e.CommandName.ToString() = 'Show' Then
Response.Write(e.Item.Cells(5).Text)
EndIfEndSub’ItemCmd
C#
protectedvoidItemCmd(Object source, System.Web.UI.WebControls.DataGridCommandEventArgs e )
{
if (e.CommandName.ToString () == 'Show')
{
Response.Write( e.Item.Cells[5].Text );
}
}
Dim mycn As SqlConnection
Dim myda As SqlDataAdapter
Dim ds As DataSet
Dim strConn, strSQL AsStringPrivateSub Page_Load(sender AsObject, e As System.EventArgs)
strConn = 'server=localhost;uid=sa;database=northwind;pwd=;'IfNot Page.IsPostBack Then
BindGrid()
EndIfEndSub’Page_LoadSub BindGrid()
mycn = New SqlConnection(strConn)
strSQL = 'Select * from Region'
myda = New SqlDataAdapter(strSQL, mycn)
ds = New DataSet()
myda.Fill(ds, 'Table')
DataGrid1.DataSource = ds
DataGrid1.DataBind()
EndSub’BindGridPublicSub DataGrid1_Cancel(sender As [Object], e As DataGridCommandEventArgs)
DataGrid1.EditItemIndex = - 1
BindGrid()
EndSub’DataGrid1_CancelPublicSub DataGrid1_Edit(sender As [Object], e As DataGridCommandEventArgs)
DataGrid1.EditItemIndex = CInt(e.Item.ItemIndex)
BindGrid()
EndSub’DataGrid1_EditPublicSub DataGrid1_Delete(sender As [Object], e As DataGridCommandEventArgs)
Dim orderid AsInteger = CInt(DataGrid1.DataKeys(CInt(e.Item.ItemIndex)))
Dim deleteCmd As [String] = 'DELETE from Region where Regionid = @Regionid 'Dim cn AsNew SqlConnection(strConn)
Dim myCommand AsNew SqlCommand(deleteCmd, cn)
myCommand.Parameters.Add(New SqlParameter('@Regionid', SqlDbType.Int))
myCommand.Parameters('@Regionid').Value = DataGrid1.DataKeys(CInt(e.Item.ItemIndex))
myCommand.Connection.Open()
Try
myCommand.ExecuteNonQuery()
Catch
lblError.Text = 'ERROR: Could not delete record'EndTry
myCommand.Connection.Close()
BindGrid()
EndSub’DataGrid1_Delete
C#
SqlConnection mycn;
SqlDataAdapter myda;
DataSet ds;
string strConn,strSQL;
privatevoidPage_Load(object sender, System.EventArgs e)
{
strConn ='server=localhost;uid=sa;database=northwind;pwd=;';
if (!Page.IsPostBack )
{
BindGrid();
}
}
voidBindGrid()
{
mycn = new SqlConnection(strConn);
strSQL = 'Select * from Region' ;
myda = new SqlDataAdapter (strSQL, mycn);
ds= new DataSet ();
myda.Fill (ds,'Table');
DataGrid1.DataSource =ds;
DataGrid1.DataBind ();
}
publicvoidDataGrid1_Cancel(Object sender, DataGridCommandEventArgs e)
{
DataGrid1.EditItemIndex = -1;
BindGrid();
}
publicvoidDataGrid1_Edit(Object sender, DataGridCommandEventArgs e)
{
DataGrid1.EditItemIndex = (int)e.Item.ItemIndex;
BindGrid();
}
publicvoidDataGrid1_Delete(Object sender, DataGridCommandEventArgs e)
{
int orderid=(int) DataGrid1.DataKeys[(int)e.Item.ItemIndex];;
String deleteCmd = 'DELETE from Region where Regionid = @Regionid ';
SqlConnection cn = new SqlConnection (strConn);
SqlCommand myCommand = new SqlCommand(deleteCmd, cn);
myCommand.Parameters.Add(new SqlParameter('@Regionid', SqlDbType.Int ));
myCommand.Parameters['@Regionid'].Value = DataGrid1.DataKeys[(int)e.Item.ItemIndex];
myCommand.Connection.Open();
try
{
myCommand.ExecuteNonQuery();
}
catch (SqlException)
{
lblError.Text = 'ERROR: Could not delete record';
}
myCommand.Connection.Close();
BindGrid();
}
Dim cn As SqlConnection
Dim da As SqlDataAdapter
Dim ds As DataSet
PrivateSub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
’ Put user code to initialize the page here
cn = New SqlConnection('server=localhost;uid=sa;pwd=;database=northwind')
da = New SqlDataAdapter('Select * from orders where orderid=10248', cn)
ds = New DataSet()
da.Fill(ds, 'Orders')
DataGrid1.DataSource = GoDoReShape(ds)
DataGrid1.DataBind()
EndSub’Page_LoadPublicFunction GoDoReShape(ByVal ds As DataSet) As DataSet
Dim NewDs AsNew DataSet()
NewDs.Tables.Add()
’Create Two Columns with names 'ColumnName' and 'Value'’ColumnName -> Displays all ColumnNames’Value -> Displays ColumnData
NewDs.Tables(0).Columns.Add('ColumnName')
NewDs.Tables(0).Columns.Add('Value')Dim dr As DataRow
ForEach dr In ds.Tables(0).Rows
Dim dcol As System.Data.DataColumn
ForEach dcol In ds.Tables(0).Columns
’Declare ArrayDim MyArray AsString() = {dcol.ColumnName.ToString(), dr(dcol.ColumnName.ToString()).ToString()}
NewDs.Tables(0).Rows.Add(MyArray)
NextNextReturn NewDs
EndFunction’GoDoReShape
C#
SqlConnection cn ;
SqlDataAdapter da;
DataSet ds;
privatevoidPage_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
cn =new SqlConnection('server=localhost;uid=sa;pwd=;database=northwind');
da=new SqlDataAdapter ( 'Select * from orders where orderid=10248',cn);
ds = new DataSet();
da.Fill (ds,'Orders');
DataGrid1.DataSource =GoDoReShape (ds);
DataGrid1.DataBind ();
}
public DataSet GoDoReShape(DataSet ds)
{
DataSet NewDs=new DataSet();
NewDs.Tables.Add();
//Create Two Columns with names 'ColumnName' and 'Value'//ColumnName -> Displays all ColumnNames//Value -> Displays ColumnData
NewDs.Tables[0].Columns.Add('ColumnName');
NewDs.Tables[0].Columns.Add('Value');
foreach(DataRow dr in ds.Tables [0].Rows )
{
foreach(System.Data.DataColumn dcol in ds.Tables[0].Columns)
{
//Declare Arraystring[] MyArray={dcol.ColumnName.ToString(),dr[dcol.ColumnName.ToString()].ToString()};
NewDs.Tables[0].Rows.Add(MyArray);
}
}
return NewDs;
}
protectedboolCheckStatus(bool prdStatus)
{
//If the Discontinued field is '0'if (prdStatus==false)
{
returntrue;
}
//If the Discontinued field is '1'else
{
returnfalse;
}
}
Dim sqlStmt AsStringDim conString AsStringDim cn As SqlConnection
Dim cmd As SqlCommand
PrivateSub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
’ Put user code to initialize the page hereIfNot Page.IsPostBack Then
BindGrid()
EndIfEndSub’Page_LoadSub BindGrid()
’Bind the Datagrid with dataSetEndSub’BindGridProtectedSub EditCmd(ByVal sender AsObject, ByVal e As DataGridCommandEventArgs)
DataGrid1.EditItemIndex = CInt(e.Item.ItemIndex)
BindGrid()
EndSub’EditCmdPublicSub CancelCmd(ByVal sender AsObject, ByVal e As DataGridCommandEventArgs)
DataGrid1.EditItemIndex = -1
BindGrid()
EndSub’CancelCmdProtectedSub UpdateCmd(ByVal sender AsObject, ByVal e As DataGridCommandEventArgs)
If Page.IsValid Then
sqlStmt = 'UPDATE Employees SET LastName = @LastName, FirstName=@FirstName,Title=@Title where EmployeeId = @EmployeeId'
conString = 'server=localhost;database=Northwind;uid=sa;pwd=;'
cn = New SqlConnection(conString)
cmd = New SqlCommand(sqlStmt, cn)
Dim LastName, FirstName, Title AsString
LastName = CType(e.Item.FindControl('txtLastName'), TextBox).Text
FirstName = CType(e.Item.FindControl('txtFirstName'), TextBox).Text
Title = CType(e.Item.FindControl('txtTitle'), TextBox).TextDim EmployeeId AsInteger = CInt(DataGrid1.DataKeys(CInt(e.Item.ItemIndex)))
cmd.Parameters.Add(New SqlParameter('@LastName', LastName))
cmd.Parameters.Add(New SqlParameter('@FirstName', FirstName))
cmd.Parameters.Add(New SqlParameter('@Title', Title))
cmd.Parameters.Add(New SqlParameter('@EmployeeId', EmployeeId))Try
cn.Open()
cmd.ExecuteNonQuery()
DataGrid1.EditItemIndex = -1Catch ex As Exception
Response.Write(ex.Message.ToString())
EndTry
BindGrid()
EndIfEndSub’UpdateCmd
PrivateSub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
’Put user code to initialize the page hereIfNot Page.IsPostBack Then
BindDataGrid('ProductId')EndIfEndSubProtectedSub SortData(ByVal source AsObject, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs)
BindDataGrid(e.SortExpression.ToString())
EndSubSub BindDataGrid(ByVal sortfield AsString)
ViewState('SortExpression') = sortfield’Fill the DataSetDim dv As DataView = ds.Tables(0).DefaultView
dv.Sort = sortfield
DataGrid1.DataSource = dv
DataGrid1.DataBind()
EndSubProtectedSub ItemDB(ByVal sender AsObject, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)
Dim dv As DataView = DataGrid1.DataSource
Dim dc As DataColumnCollection = dv.Table.Columns
If e.Item.ItemType = ListItemType.Header ThenIf ViewState('SortExpression') <> '' Then
e.Item.Cells(dc.IndexOf(dc(ViewState('SortExpression')))).BackColor = Color.BlueViolet
e.Item.Cells(dc.IndexOf(dc(ViewState('SortExpression')))).ForeColor = Color.AntiqueWhiteEndIfEndIfEndSub
C#
privatevoidPage_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page hereif(! Page.IsPostBack )
{
BindDataGrid('ProductId');
}
}
protectedvoidSortData(Object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e )
{
BindDataGrid(e.SortExpression.ToString());
}
voidBindDataGrid(string sortfield)
{
ViewState['SortExpression'] = sortfield;
//Fill the dataset
DataView dv = ds.Tables[0].DefaultView;
dv.Sort = sortfield;
DataGrid1.DataSource = dv;
DataGrid1.DataBind();
}
protectedvoidItemDB(object sender ,System.Web.UI.WebControls.DataGridItemEventArgs e )
{
DataView dv =(DataView) DataGrid1.DataSource;
DataColumnCollection dc = dv.Table.Columns;
if (e.Item.ItemType == ListItemType.Header )
{
if (ViewState['SortExpression'].ToString()!= '')
{
e.Item.Cells[dc.IndexOf( dc[ViewState['SortExpression'].ToString ()])].BackColor = Color.BlueViolet;
e.Item.Cells[dc.IndexOf(dc[ViewState['SortExpression'].ToString ()])].ForeColor = Color.AntiqueWhite;
}
}
}
Step 1: Display the Data in the Datagrid
Initially the Datagrid is populated with the records in the db
The field Discontinued is of data type bit in the db i.e 0/1.
To display it as yes/no in the Datagrid a helper function ShowVal(…) is called
Step 2: To Edit the Datagrid ,
When the edit button is clicked it should display field Discontinued as Yes/No
To update the record the user should get a choice to Select Yes/No using dropdownlist
By default the dropdownlist should be set to the value in the database
So the DataSource property of the dropdownlist is set to BindTheDiscontinued()
and OnPreRender property does the task of setting the value from the db to the dropdownlist
Dim strDiscontinued AsStringDim obj As GetData
Dim strSql AsStringDim strConn AsStringDim ds As DataSet
Dim dr As SqlDataReader
PrivateSub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
’ Put user code to initialize the page here
strConn = 'server=localhost;uid=sa;pwd=;database=northwind'IfNot Page.IsPostBack Then
BindGrid()
EndIfEndSub’Page_Load’To Bind the DataGridSub BindGrid()
obj = New GetData
strSql = 'Select productid, discontinued from Products'
ds = obj.GetDataFromTable(strSql, strConn)
DataGrid1.DataSource = ds
DataGrid1.DataBind()
EndSub’BindGrid’To display Yes/No for True/FalseProtectedFunction ShowVal(ByVal blnval AsBoolean) AsStringIf blnval = TrueThenReturn'Yes'ElseReturn'No'EndIfEndFunction’ShowVal’Bind the Data to the dropdownlist in the EditTemplateProtectedFunction BindTheDiscontinued() As SqlDataReader
obj = New GetData
strSql = 'SELECT distinct ’Discontinued’ ='
strSql += ' CASE '
strSql += ' WHEN Discontinued = 1 Then ’Yes’'
strSql += ' ELSE ’No’'
strSql += ' END '
strSql += ' From Products '
dr = obj.GetSingleDataUsingReader(strSql, strConn)
Return dr
EndFunction’BindTheDiscontinued’Set the Text of the Dropdownlist to the field value in DatabaseProtectedSub SetDropDownIndex(ByVal sender As [Object], ByVal e As System.EventArgs)
Dim ed As DropDownList
ed = CType(sender, DropDownList)
ed.SelectedIndex = ed.Items.IndexOf(ed.Items.FindByText(strDiscontinued))
EndSub’SetDropDownIndex’For Edit Update CancelPublicSub DataGrid1_Edit(ByVal sender As [Object], ByVal e As DataGridCommandEventArgs)
strDiscontinued = CType(e.Item.FindControl('lblDiscontinued'), Label).Text
DataGrid1.EditItemIndex = CInt(e.Item.ItemIndex)
BindGrid()
EndSub’DataGrid1_EditPublicSub DataGrid1_Update(ByVal sender As [Object], ByVal e As DataGridCommandEventArgs)
Dim TempList As DropDownList
Dim TempValue As [String]
TempList = CType(e.Item.FindControl('ddlDiscontinued'), DropDownList)
TempValue = TempList.SelectedItem.Value
’Place update code here
Response.Write(TempValue)
DataGrid1.EditItemIndex = -1
BindGrid()
EndSub’DataGrid1_UpdatePublicSub DataGrid1_Cancel(ByVal sender As [Object], ByVal e As DataGridCommandEventArgs)
DataGrid1.EditItemIndex = -1
BindGrid()
EndSub’DataGrid1_Cancel’Functions used in Class GetData.csDim mycn As SqlConnection
Dim myda As SqlDataAdapter
Dim mycmd As SqlCommand
Dim ds As DataSet
Dim strConn AsStringDim myReader As SqlDataReader
PublicFunction GetDataFromTable(ByVal strSQL AsString, ByVal strConnString AsString) As DataSet
Try
strConn = strConnString
mycn = New SqlConnection(strConn)
myda = New SqlDataAdapter(strSQL, mycn)
ds = New DataSet
myda.Fill(ds, 'Table')Return ds
Catch ex As Exception
ThrowNew Exception(ex.Message.ToString())
Finally
mycn.Close()
EndTryEndFunction’GetDataFromTablePublicFunction GetSingleDataUsingReader(ByVal strSQL AsString, ByVal strConnString AsString) As SqlDataReader
Try
strConn = strConnString
mycn = New SqlConnection(strConn)
mycmd = New SqlCommand(strSQL, mycn)
mycn.Open()
myReader = mycmd.ExecuteReader(CommandBehavior.CloseConnection)
Return myReader
Catch ex As Exception
ThrowNew Exception(ex.Message.ToString())
FinallyEndTry’mycn.Close ();EndFunction’GetSingleDataUsingReader
C#
string strDiscontinued;
GetData obj;
string strSql;
string strConn;
DataSet ds;
SqlDataReader dr;
privatevoidPage_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
strConn ='server=localhost;uid=sa;pwd=;database=northwind';
if (!Page.IsPostBack )
{
BindGrid();
}
}
//To Bind the DataGridvoidBindGrid()
{
obj=new GetData ();
strSql = 'Select productid, discontinued from Products';
ds=obj.GetDataFromTable (strSql ,strConn);
DataGrid1.DataSource =ds;
DataGrid1.DataBind ();
}
//To display Yes/No for True/FalseprotectedstringShowVal(bool blnval)
{
if (blnval==true)
{
return'Yes';
}
else
{
return'No';
}
}
//Bind the Data to the dropdownlist in the EditTemplateprotected SqlDataReader BindTheDiscontinued()
{
obj=new GetData ();
strSql ='SELECT distinct ’Discontinued’ =' ;
strSql+=' CASE ';
strSql+=' WHEN Discontinued = 1 Then ’Yes’' ;
strSql+=' ELSE ’No’' ;
strSql+=' END ' ;
strSql+=' From Products ';
dr=obj.GetSingleDataUsingReader (strSql ,strConn);
return dr;
}
//Set the Text of the Dropdownlist to the field value in DatabaseprotectedvoidSetDropDownIndex(Object sender ,System.EventArgs e )
{
DropDownList ed ;
ed = (DropDownList) sender;
ed.SelectedIndex = ed.Items.IndexOf(ed.Items.FindByText(strDiscontinued));
}
//For Edit Update CancelpublicvoidDataGrid1_Edit(Object sender, DataGridCommandEventArgs e)
{
strDiscontinued = ((Label )e.Item.FindControl('lblDiscontinued')).Text;
DataGrid1.EditItemIndex = (int)e.Item.ItemIndex;
BindGrid();
}
publicvoidDataGrid1_Update(Object sender, DataGridCommandEventArgs e)
{
DropDownList TempList ;
String TempValue ;
TempList = (DropDownList) e.Item.FindControl('ddlDiscontinued');
TempValue = TempList.SelectedItem.Value;
//Place update code here
Response.Write (TempValue);
DataGrid1.EditItemIndex = -1;
BindGrid();
}
publicvoidDataGrid1_Cancel(Object sender, DataGridCommandEventArgs e)
{
DataGrid1.EditItemIndex = -1;
BindGrid();
}
//Functions used in Class GetData.cs
SqlConnection mycn;
SqlDataAdapter myda;
SqlCommand mycmd;
DataSet ds;
String strConn;
SqlDataReader myReader;
public DataSet GetDataFromTable(string strSQL ,string strConnString)
{
try
{
strConn=strConnString;
mycn = new SqlConnection(strConn);
myda = new SqlDataAdapter (strSQL, mycn);
ds= new DataSet ();
myda.Fill (ds,'Table');
return ds;
}
catch(Exception ex)
{
thrownew Exception (ex.Message.ToString ());
}
finally
{
mycn.Close ();
}
}
public SqlDataReader GetSingleDataUsingReader(string strSQL ,string strConnString)
{
try
{
strConn=strConnString;
mycn = new SqlConnection(strConn);
mycmd = new SqlCommand (strSQL, mycn);
mycn.Open ();
myReader=mycmd.ExecuteReader(CommandBehavior.CloseConnection );
return myReader;
}
catch(Exception ex)
{
thrownew Exception (ex.Message.ToString ());
}
finally
{
//mycn.Close ();
}
}
PrivateSub Page_Load(sender AsObject, e As System.EventArgs)
’ Put user code to initialize the page hereIfNot Page.IsPostBack Then’Populate the DataGridEndIfEndSub’Page_Load ProtectedSub ItemDB(ByVal s AsObject, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem ThenIf e.Item.Cells(1).Text = ' ' Then
e.Item.Cells(1).Text = 'No data'EndIfEndIfEndSub’ItemDB
C#
privatevoidPage_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page hereif(!Page.IsPostBack )
{
//Populate the DataGrid
}
}
protectedvoidItemDB (Object s , System.Web.UI.WebControls.DataGridItemEventArgs e )
{
if ((e.Item.ItemType ==ListItemType.Item) ||(e.Item.ItemType ==ListItemType.AlternatingItem))
{
if( e.Item.Cells[1].Text == ' ')
{
e.Item.Cells[1].Text = 'No data';
}
}
}
PrivateSub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
’Put user code to initialize the page hereIfNot Page.IsPostBack Then’Populate the DataGridEndIfEndSubProtectedSub ItemCmd(ByVal source AsObject, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs)
If e.CommandName = 'Show' Then
Response.Write(e.Item.Cells(1).Text)
EndIfEndSub
C#
privatevoidPage_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page hereif (!Page.IsPostBack )
{
//Populate the DataGrid
}
}
protectedvoidItemCmd(Object source , System.Web.UI.WebControls.DataGridCommandEventArgs e )
{
if (e.CommandName.ToString () == 'Show')
{
Response.Write(e.Item.Cells[1].Text);
}
}
Dim sqlStmt AsStringDim conString AsStringDim cn As SqlConnection = NothingDim da As SqlDataAdapter = NothingDim ds As DataSet
PrivateSub Page_Load(sender AsObject, e As System.EventArgs)
conString = 'server=localhost;database=Northwind;uid=sa;pwd=;'
cn = New SqlConnection(conString)
IfNot Page.IsPostBack Then
BindData()
EndIfEndSub’Page_LoadSub BindData()
sqlStmt = 'select * from emp '
ds = New DataSet()
da = New SqlDataAdapter(sqlStmt, cn)
da.Fill(ds, 't1')
DataGrid1.DataSource = ds
DataGrid1.DataBind()
EndSub’BindDataProtectedSub ItemCrt(sender AsObject, e As DataGridItemEventArgs)
SelectCase e.Item.ItemType
Case ListItemType.Item, ListItemType.AlternatingItem
Dim btn As Button = CType(e.Item.Cells(0).Controls(0), Button)
btn.Attributes.Add('onclick', 'return confirm(’are you sure you want to delete this’)')ExitEndSelectEndSub’ItemCrtProtectedSub DelCmd(sender As [Object], e As DataGridCommandEventArgs)
DeleteRow(Me.DataGrid1.DataKeys(e.Item.ItemIndex).ToString())
BindData()
EndSub’DelCmdPrivateSub DeleteRow(empid AsString)
Dim cmd AsNew SqlCommand('DELETE FROM Emp WHERE employeeid =' + empid, cn)
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
EndSub’DeleteRow
C#
string sqlStmt ;
string conString ;
SqlConnection cn =null;
SqlDataAdapter da =null;
DataSet ds;
privatevoidPage_Load(object sender, System.EventArgs e)
{
conString = 'server=localhost;database=Northwind;uid=sa;pwd=;';
cn = new SqlConnection(conString);
if (!Page.IsPostBack )
{
BindData();
}
}
voidBindData()
{
sqlStmt = 'select * from emp ';
ds= new DataSet ();
da = new SqlDataAdapter (sqlStmt, cn);
da.Fill (ds,'t1');
DataGrid1.DataSource =ds;
DataGrid1.DataBind ();
}
protectedvoidItemCrt(object sender, DataGridItemEventArgs e)
{
switch(e.Item.ItemType)
{
case ListItemType.Item:
case ListItemType.AlternatingItem:
{
Button btn = (Button)e.Item.Cells[0].Controls[0];
btn.Attributes.Add('onclick',
'return confirm(’are you sure you want to delete this’)');
break;
}
}
}
protectedvoidDelCmd(Object sender , DataGridCommandEventArgs e )
{
DeleteRow (this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString());
BindData();
}
privatevoidDeleteRow(string empid)
{
SqlCommand cmd = new SqlCommand('DELETE FROM Emp WHERE employeeid ='+ empid ,cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
How to confirm delete in DataGrid using LinkButton
<script>functionconfirmmsg()
{
if (confirm('Do you want to delete record?')==true)
returntrue;
elsereturnfalse;
}
</script><asp:DataGridid='DataGrid1'AutoGenerateColumns='False'DataKeyField='Employeeid'OnItemCommand='ItemCmd'OnItemDataBound='ItemDB'runat='server'><Columns><asp:BoundColumnDataField='firstname'HeaderText='First Name'></asp:BoundColumn><asp:TemplateColumn><ItemTemplate><asp:LinkButtonid='btnDelete'runat='server'Text='Delete'CommandName='Delete'CausesValidation='false'></asp:LinkButton></ItemTemplate></asp:TemplateColumn></Columns></asp:DataGrid>
VB.NET
Dim sqlStmt AsStringDim conString AsStringDim cn As SqlConnection = NothingDim da As SqlDataAdapter = NothingDim ds As DataSet
PrivateSub Page_Load(sender AsObject, e As System.EventArgs)
conString = 'server=localhost;database=Northwind;uid=sa;pwd=;'
cn = New SqlConnection(conString)
IfNot Page.IsPostBack Then
BindData()
EndIfEndSub’Page_LoadSub BindData()
sqlStmt = 'select * from emp '
ds = New DataSet()
da = New SqlDataAdapter(sqlStmt, cn)
da.Fill(ds, 't1')
DataGrid1.DataSource = ds
DataGrid1.DataBind()
EndSub’BindDataProtectedSub ItemDB(sender AsObject, e As System.Web.UI.WebControls.DataGridItemEventArgs)
SelectCase e.Item.ItemType
Case ListItemType.Item, ListItemType.AlternatingItem
Dim btn As LinkButton = CType(e.Item.FindControl('btnDelete'), LinkButton)
btn.Attributes.Add('onclick', 'return confirmmsg();')ExitEndSelectEndSub’ItemDBProtectedSub ItemCmd(sender AsObject, e As System.Web.UI.WebControls.DataGridCommandEventArgs)
If e.CommandName = 'Delete' ThenMe.DeleteRow(Me.DataGrid1.DataKeys(e.Item.ItemIndex).ToString())
EndIf
BindData()
EndSub’ItemCmdPrivateSub DeleteRow(empid AsString)
Dim cmd AsNew SqlCommand('DELETE FROM Emp WHERE employeeid =' + empid, cn)
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
EndSub’DeleteRow
C#
string sqlStmt ;
string conString ;
SqlConnection cn =null;
SqlDataAdapter da =null;
DataSet ds;
privatevoidPage_Load(object sender, System.EventArgs e)
{
conString = 'server=localhost;database=Northwind;uid=sa;pwd=;';
cn = new SqlConnection(conString);
if (!Page.IsPostBack )
{
BindData();
}
}
voidBindData()
{
sqlStmt = 'select * from emp ';
ds= new DataSet ();
da = new SqlDataAdapter (sqlStmt, cn);
da.Fill (ds,'t1');
DataGrid1.DataSource =ds;
DataGrid1.DataBind ();
}
protectedvoidItemDB(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
switch(e.Item.ItemType)
{
case ListItemType.Item:
case ListItemType.AlternatingItem:
{
LinkButton btn = (LinkButton)e.Item.FindControl('btnDelete');
btn.Attributes.Add('onclick', 'return confirmmsg();');
break;
}
}
}
protectedvoidItemCmd(object sender, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if(e.CommandName == 'Delete')
{
this.DeleteRow(this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString());
}
BindData();
}
privatevoidDeleteRow(string empid)
{
SqlCommand cmd = new SqlCommand('DELETE FROM Emp WHERE employeeid ='+ empid ,cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
PrivateSub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
’Put user code to initialize the page hereIfNot Page.IsPostBack Then
Binddata()
EndIfEndSubProtectedSub PageData(ByVal source AsObject, ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs)
DataGrid1.CurrentPageIndex = e.NewPageIndex
Binddata()
EndSubSub Binddata()
’Populate the DataGrid using DataSetEndSub
C#
privatevoidPage_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page hereif(! Page.IsPostBack )
{
Binddata();
}
}
protectedvoidPageData(Object source , System.Web.UI.WebControls.DataGridPageChangedEventArgs e )
{
DataGrid1.CurrentPageIndex = e.NewPageIndex;
Binddata();
}
voidBinddata()
{
//Populate the DataGrid using DataSet
}
PrivateSub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
’Put user code to initialize the page hereIfNot Page.IsPostBack Then
BindDataGrid('ProductId')EndIfEndSubProtectedSub SortData(ByVal source AsObject, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs)
BindDataGrid(e.SortExpression.ToString())
EndSubSub BindDataGrid(ByVal sortfield AsString)
’Fill the Dataset’.....Dim dv As DataView = ds.Tables(0).DefaultView
dv.Sort = sortfield
DataGrid1.DataSource = dv
DataGrid1.DataBind()
EndSub
C#
privatevoidPage_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page hereif(! Page.IsPostBack )
{
BindDataGrid('ProductId');
}
}
protectedvoidSortData(Object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e )
{
BindDataGrid(e.SortExpression.ToString());
}
voidBindDataGrid(string sortfield)
{
//Fill the Dataset//.....
DataView dv = ds.Tables[0].DefaultView;
dv.Sort = sortfield;
DataGrid1.DataSource = dv;
DataGrid1.DataBind();
}
Dim cn As SqlConnection
Dim da As SqlDataAdapter
Dim ds As DataSet
PrivateSub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
cn = New SqlConnection('Server=localhost;uid=sa;pwd=;database=northwind')
da = New SqlDataAdapter('Select * from products', cn)
ds = New DataSet
da.Fill(ds, 'Products')
DataGrid1.DataSource = ds.Tables(0)
’DataGrid1.DataSource = ds’DataGrid1.DataSource = ds.Tables('Product')
DataGrid1.DataBind()
EndSub
C#
SqlConnection cn;
SqlDataAdapter da;
DataSet ds;
privatevoidPage_Load(object sender, System.EventArgs e)
{
cn= new SqlConnection ('Server=localhost;uid=sa;pwd=;database=northwind');
da= new SqlDataAdapter ('SELECT * FROM Products ', cn);
ds= new DataSet ();
da.Fill (ds, 'Product');
DataGrid1.DataSource =ds.Tables[0];
//DataGrid1.DataSource= ds;//DataGrid1.DataSource= ds.Tables['Products'];
DataGrid1.DataBind ();
}
Dim cn As SqlConnection
Dim cmd As SqlCommand
Dim rdr As SqlDataReader
PrivateSub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load
’Put user code to initialize the page hereTry
cn = New SqlConnection('server=localhost;uid=sa;pwd=;database=northwind')
cmd = New SqlCommand('select * from employees ', cn)
cn.Open()
rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
DataGrid1.DataSource = rdr
DataGrid1.DataBind()
Catch ex As Exception
Response.Write(ex.Message.ToString())
Finally
rdr.Close()
cn.Close()
EndTryEndSub’Page_Load
C#
SqlConnection cn ;
SqlCommand cmd ;
SqlDataReader rdr ;
privatevoidPage_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page heretry
{
cn = new SqlConnection('server=localhost;uid=sa;pwd=;database=northwind');
cmd = new SqlCommand( 'select * from employees ', cn);
cn.Open();
rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection );
DataGrid1.DataSource = rdr;
DataGrid1.DataBind();
}
catch (Exception ex)
{
Response.Write (ex.Message.ToString ());
}
finally
{
rdr.Close();
cn.Close();
}
}
How to set a Datagrid Column to invisible when that Column is an AutoGeneratedColumn
In the DataGrid’s declaration, add the following code in OnItemDataBound event
VB.NET
Dim dv As DataView = DataGrid1.DataSource ’Bind you DataGrid1 in Page_Load to DataViewDim dc As DataColumnCollection = dv.Table.Columns
e.Item.Cells(dc.IndexOf(dc('field_name))).Visible = false
C#
DataView dv = DataGrid1.DataSource ;//Bind you DataGrid1 in Page_Load to DataView
DataColumnCollection dc = dv.Table.Columns;
e.Item.Cells[dc.IndexOf(dc['field_name'])].Visible = false;
How to hide a row in a DataGrid if one of the Column value is zero
VB.NET
ProtectedSub ItemDB(sender AsObject, e As System.Web.UI.WebControls.DataGridItemEventArgs)
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.Item ThenIf e.Item.Cells(8).Text = '0' Then
e.Item.Visible = FalseEndIfEndIfEndSub’ItemDB
How to display a Tooltip when hovering over the Header sort link of the DataGrid
ProtectedSub ItemDB(sender AsObject, e As System.Web.UI.WebControls.DataGridItemEventArgs)
Dim i AsIntegerFor i = 0To e.Item.Cells.Count - 1
e.Item.Cells(i).ToolTip = 'This is Column ' + i.ToString()NextEndSub’ItemDB
Why do I get a blank page when I click the linkbutton in the Datagrid, I am also handling PostBack on the page? The ItemCommand Event does not seem to trigger
You must have set the EnableViewState property of DataGrid to false
Share with