Live Chat Icon For mobile
Live Chat Icon

ASP.NET FAQ

Find answers for the most frequently asked questions
Expand All Collapse All

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:


<ItemStyle Wrap='False'></ItemStyle>

For more details refer

  • Microsoft Knowledge Base Article – 323169
  • Microsoft Knowledge Base Article – 324165
Permalink

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.

For more details refer How To Export Data in a DataGrid on an ASP . NET WebForm to Microsoft Excel

Permalink

<asp:DataGrid id='DataGrid1' OnItemDataBound ='ItemDB' runat='server'></asp:DataGrid>

VB.NET


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
	’ Put user code to initialize the page here
        	If Not Page.IsPostBack Then
            		’Populate the dataSet
            		’Bind the dataGrid with the dataView
            		DataGrid1.DataSource = BindTheDataClass.Binddata().Tables(0).DefaultView
            		DataGrid1.DataBind()
        	End If
End Sub ’Page_Load

Protected Sub ItemDB(ByVal sender As Object, 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 = 0 Then
            		’By default the Datagrid Header is shown in case there is no Data Available
            		’So in case of No Data found 
            		’Check the ListItemType.Header
            		If e.Item.ItemType = ListItemType.Header Then
	                	Dim i As Integer = 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 Datagrid
		                Dim j As Integer
		                For j = i - 1 To 1 Step -1
			                    e.Item.Cells.RemoveAt(j)
		                Next 
          	  	End If
        	End If
End Sub ’ItemDB

C#


private void Page_Load(object sender, System.EventArgs e)
{
	// Put user code to initialize the page	here
	if (!Page.IsPostBack )
	{
		//Fill DataSet
		//Bind the DataGrid with the DataView
		DataGrid1.DataSource =ds.Tables[0].DefaultView ;
		DataGrid1.DataBind ();
	}
}

protected void ItemDB(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.Header
		if ((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 Datagrid
			for (int j=i-1;j>0;j--)
			{
				e.Item.Cells.RemoveAt(j);
			}
		}
	}
}
Permalink

You could get this error for the following reasons:

  1. 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.
  2. 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.
Permalink

Method 1 : Set the HeaderText Property of the BoundColumn/TemplateColumn


<asp:DataGrid id='DataGrid1' AutoGenerateColumns='False' runat='server'>
<Columns>
	<asp:BoundColumn DataField='EmployeeID' HeaderText='Employee ID'>
	</asp:BoundColumn>
	<asp:BoundColumn DataField='FirstName' HeaderText='First Name'>
	</asp:BoundColumn>
	<asp:TemplateColumn HeaderText='LastName'>
	<ItemTemplate>
		<#%DataBinder.Eval(Container.DataItem, 'LastName').ToString()%>
	</ItemTemplate>
	</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

Method 2 : Dynamically change the HeaderText in the ItemDataBound Event of the DataGrid


<asp:DataGrid id='DataGrid1' OnItemDataBound='ItemDB' runat='server'></asp:DataGrid>

VB.NET


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
’Populate the DataGrid
End Sub

protected Sub ItemDB(ByVal sender As Object, 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'
End If
End Sub

C#


private void Page_Load(object sender, System.EventArgs e)
{
//Populate the DataGrid
}

protected void ItemDB(Object sender  ,System.Web.UI.WebControls.DataGridItemEventArgs e   ) 
{
	if (e.Item.ItemType == ListItemType.Header)
	{
		e.Item.Cells[0].Text = 'Employee ID';
		e.Item.Cells[1].Text = 'First Name';
		e.Item.Cells[2].Text = 'Last Name';
	}
}
Permalink

<asp:datagrid id='DataGrid1' ShowHeader =false AutoGenerateColumns =true  runat='server'   DataKeyField='OrderId' OnItemDataBound='ItemDB'>
	<Columns>
		<asp:TemplateColumn >
			<ItemTemplate>
				<b><%#DataBinder.Eval(Container.DataItem,'OrderId')%></b>
			</ItemTemplate>
		</asp:TemplateColumn>
	</Columns>
</asp:datagrid>

VB.NET


Dim cn As SqlConnection
Dim da As SqlDataAdapter
Dim ds As DataSet

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
	’ Put user code to initialize the page here
	cn = New SqlConnection('Server=localhost;uid=sa;pwd=;database=northwind')
	If Not Page.IsPostBack Then
		da = New SqlDataAdapter('SELECT orderid FROM orders', cn)
		ds = New DataSet
		da.Fill(ds, 'Orders')
		DataGrid1.DataSource = ds
		DataGrid1.DataBind()
	End If
End Sub ’Page_Load

Protected Sub ItemDB(ByVal sender As Object, ByVal e As DataGridItemEventArgs)
	If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
		Dim dgDetails As New DataGrid
		Dim orderid As Integer = CInt(CType(e.Item.DataItem, DataRowView)('OrderID'))
		dgDetails.DataSource = GetOrderDetails(orderid)
		dgDetails.DataBind()
		e.Item.Cells(1).Controls.Add(dgDetails)
	End If
End Sub ’ItemDB

Function GetOrderDetails(ByVal id As Integer) As DataSet
	da = New SqlDataAdapter('SELECT * FROM [Order Details] where orderid=' + id.ToString, cn)
	ds = New DataSet
	da.Fill(ds, 'OrderDetails')
	Return ds
End Function ’GetOrderDetails

C#


SqlConnection cn;
SqlDataAdapter da;
DataSet ds;
private void Page_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 (); 
	}
}

protected void ItemDB(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;
}
Permalink

<asp:DataGrid id='DataGrid1' OnItemCommand='ItemCommand' 
style='Z-INDEX: 101; LEFT: 15px; POSITION: absolute; TOP: 23px'
 runat='server'  >
	<Columns>
		<asp:ButtonColumn Text='Edit' ButtonType='PushButton' CommandName='Edit'>
</asp:ButtonColumn>
	</Columns>
</asp:DataGrid>
<asp:TextBox id='txtRegionID' style='Z-INDEX: 102; LEFT: 352px; POSITION: absolute; TOP: 24px'
	runat='server'></asp:TextBox>
<asp:TextBox id='txtRegionDescription' style='Z-INDEX: 103; LEFT: 352px; POSITION: absolute; TOP: 64px'
	runat='server'></asp:TextBox>
<asp:Button id='btnUpdate' style='Z-INDEX: 104; LEFT: 304px; POSITION: absolute; TOP: 128px'
	runat='server' Text='Update'></asp:Button>
<asp:Label id='lblMessage' style='Z-INDEX: 105; LEFT: 296px; POSITION: absolute; TOP: 176px'
	runat='server'></asp:Label>

VB.NET


Dim cn As SqlConnection
Dim da As SqlDataAdapter
Dim cmd As SqlCommand
Dim strsql As String
Dim ds As DataSet

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
	’Put user code to initialize the page here
	cn = New SqlConnection('Server=localhost;uid=sa;pwd=;database=northwind;')
	If Not Page.IsPostBack Then
		BindData()
	End If
End Sub

Sub BindData()
	DataGrid1.DataSource = GetData('Select * from Region')
	DataGrid1.DataBind()
End Sub

Function GetData(ByVal strSql As String) As DataSet
	da = New SqlDataAdapter(strSql, cn)
	ds = New DataSet()
	da.Fill(ds)
	Return ds
End Function

Protected Sub ItemCommand(ByVal source As Object, _
 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)
	End If
End Sub

Sub FillTheData(ByVal RegionID As String, ByVal RegionDescription As String)
	txtRegionID.Text = RegionID
	txtRegionDescription.Text = RegionDescription
End Sub

Private Sub 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()
End Try
End Sub

C#


SqlConnection cn; 
SqlDataAdapter da ; 
SqlCommand cmd ; 
string strsql ;	
DataSet ds ; 
private void Page_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();
	}
}

void BindData()
{
	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;
}

protected void ItemCommand(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=''; 
	}
}	

void FillTheData(string RegionID,string RegionDescription)
{
	txtRegionID.Text = RegionID;
	txtRegionDescription.Text = RegionDescription;
}
		
private void btnUpdate_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();
}
}


Permalink

You probably declared the event handler for OnPageIndexChanged event incorrectly. Make sure that the event handler looks like the following.


<asp:DataGrid id='DataGrid1' runat='server'... OnPageIndexChanged='<EventName>'.../>

VB.NET


protected Sub <Eventname>(ByVal source As Object, ByVal e  As System.Web.UI.WebControls.DataGridPageChangedEventArgs)  
’...
end sub

C#


protected void <EventName>(object sender , System.Web.UI.WebControls.DataGridPageChangedEventArgs)
{
//...
}
Permalink

You have to manually add a row to the table generated by the datagrid as follows.


<asp:DataGrid id='DataGrid1' OnPreRender ='dgPreRender' runat='server'></asp:DataGrid>

VB.NET


protected Sub dgPreRender(ByVal sender As Object, ByVal e As System.EventArgs)  
      	Dim dgItem As New DataGridItem(0, 0, ListItemType.Header)
      	Dim tbCell As 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)
End Sub

C#


protected void dgPreRender(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);
}
Permalink

Use namespace System.IO

VB.NET


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        	’Put user code to initialize the page here
        	’Bind the DataGrid to DataSet
        	DataGridToExcel(DataGrid1, Response)
End Sub

Protected Sub DataGridToExcel(ByVal dGridExport As DataGrid, ByVal httpResp As HttpResponse)
        	httpResp.Clear()
        	httpResp.Charset = ''
        	httpResp.ContentType = 'application/vnd.ms-excel'
        	Dim stringWrite As New StringWriter
        	Dim htmlWrite As New HtmlTextWriter(stringWrite)
        	Dim dGrid As New DataGrid
        	dGrid = dGridExport
        	dGrid.HeaderStyle.Font.Bold = True
        	dGrid.DataBind()
        	dGrid.RenderControl(htmlWrite)
        	httpResp.Write(stringWrite.ToString)
        	httpResp.End()
End Sub

C#


private void Page_Load(object sender, System.EventArgs e)
{
	// Put user code to initialize the page here
	//Bind the DataGrid to DataSet
	DataGridToExcel (DataGrid1, Response);
}
protected void DataGridToExcel(DataGrid dGridExport  ,    HttpResponse httpResp)
{
	httpResp.Clear();
	httpResp.Charset = '';
	httpResp.ContentType = 'application/vnd.ms-excel';
	StringWriter stringWrite = new  StringWriter();
	HtmlTextWriter htmlWrite = new  HtmlTextWriter(stringWrite);
	DataGrid dGrid = new DataGrid();
	dGrid = dGridExport;
	dGrid.HeaderStyle.Font.Bold = true;
	dGrid.DataBind();
	dGrid.RenderControl(htmlWrite);
	httpResp.Write(stringWrite.ToString());
	httpResp.End();
}
Permalink

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}')
End If

C#


DataSet ds = (DataSet)DataGrid1.DataSource ;
DataView dv = ds.Tables[0].DefaultView ;
DataColumnCollection dcCol  = dv.Table.Columns ; 
if ((e.Item.ItemType == ListItemType.Item )||( e.Item.ItemType == ListItemType.AlternatingItem ))
{
	e.Item.Cells[dcCol.IndexOf (dcCol ['UnitPrice'])].Text = DataBinder.Eval(e.Item.DataItem, 'UnitPrice', '{0:c}');
}
Permalink

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()).

i.e, in your template do:


<%#xxx(DataBinder.Eval(Container.DataItem, 'field_name').ToString()) %> 

VB.NET


<%#xxx(DataBinder.Eval (CStr(DataBinder.Eval(Container.DataItem, 'field_name')) )%>

C#


<%# xxx((string) DataBinder.Eval(Container.DataItem, 'field_name'))%> 

Either of these should work.

Permalink

In the ItemDataBound event you can access the Cells() collection of the current Datagrid item (or row) and set it’s ForeColor.


<asp:DataGrid OnItemDataBound='ItemDB' id='DataGrid1' runat='server'></asp:DataGrid>

VB.NET


protected Sub ItemDB(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)
If (e.Item.ItemType = ListItemType.Item Or _
                 e.Item.ItemType = ListItemType.AlternatingItem) Then
	If e.Item.DataItem(6) > 15 Then
		e.Item.Cells(6).ForeColor = System.Drawing.Color.Green
	Else
		e.Item.Cells(6).ForeColor = System.Drawing.Color.Red
	End If
End If
End Sub

C#


protected void ItemDB(object	 sender,  System.Web.UI.WebControls.DataGridItemEventArgs e) 
{
	if((e.Item.ItemType ==ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem) )
	{
	if (Convert.ToInt16 (e.Item.Cells[6].Text) >15 )
		{
		e.Item.Cells[6].ForeColor = System.Drawing.Color.Green;
		}
	else
		{
		e.Item.Cells[6].ForeColor = System.Drawing.Color.Red;
		}
	}
}

In Cells[x]/Cells(x) x=> index number to the list of fields in the row.

Permalink

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.


<asp:TemplateColumn >
<ItemTemplate>
<asp:Hyperlink ID='Hyperlink2' Runat='Server' 
NavigateUrl= <%#'javascript:my_window=window.open(’webform2.aspx?id=' + DataBinder.Eval(Container.DataItem,'productid').ToString() + '&Supplierid=' + DataBinder.Eval(Container.DataItem,'SupplierID').ToString() + '’,’my_window’,’width=300,height=300’);my_window.focus()' %> 
text=<%#DataBinder.Eval(Container.DataItem,'ProductName').ToString() %>> 
</asp:Hyperlink> 
</ItemTemplate> 
</asp:TemplateColumn>

The above approach would avoid the problem of showing the screen of [Object] on the parent page

Permalink

<asp:Datagrid id='Datagrid1' runat='server'>
<Columns> 
<asp:TemplateColumn> 
<ItemTemplate> 
<asp:Label id='Label1' Runat ='server' > <%#getCount%> </asp:Label> 
</ItemTemplate> 
</asp:TemplateColumn>
</Columns>
</asp:Datagrid>

Code behind
VB.NET


Dim count As Integer
protected function getCount() As Integer
	count = count + 1
	Return count
End Function

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
’Populate the Datagrid populating data from the database
’..... 
End Sub 

C#


int  count =0;
protected int getCount()
{
	count = count + 1;
	return count;
}

private void Page_Load(object sender, System.EventArgs e)
{
//Populate the Datagrid populating data from the database
//....
}
Permalink
  • 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.

<asp:DataGrid ShowFooter='True' OnItemCreated='ItemCreated' OnItemCommand='ItemCommand' id='DataGrid1' runat='server'></asp:DataGrid>

VB.NET


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
’ Put user	code to	initialize the page	here
	If Not Page.IsPostBack Then
		BindGrid('')
	End If
End Sub

Sub BindGrid(ByVal stralpha As String)
	Dim cn As SqlConnection
	Dim da As SqlDataAdapter
	Dim ds As DataSet
	cn = New SqlConnection('Server=localhost;uid=sa;pwd=;database=pubs')
	Dim strsql As String = 'Select * from authors '
	If stralpha = '' Then
		strsql = strsql
	Else
		strsql = strsql + '	where au_lname like’' + stralpha + '%’'
	End If
	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()
	End If
End Sub

Protected Sub ItemCreated(ByVal sender As Object, 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 As Integer
		For i = 65 To 65 + 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)
		Next
	End If
End Sub

Protected Sub ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs)
	If (e.CommandName = 'alpha') Then
		BindGrid(e.CommandArgument.ToString())
	End If
End Sub

C#


private void Page_Load(object sender, System.EventArgs e)
{
	// Put user code to	initialize the page here
	if (!Page.IsPostBack )
	{
		BindGrid('');
	}
}

void BindGrid(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 (); 
	}
}

protected void ItemCreated(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);
		}
	}
}
protected void ItemCommand(Object source   , System.Web.UI.WebControls.DataGridCommandEventArgs e) 
{
	if (e.CommandName == 'alpha' )
	{
		BindGrid(e.CommandArgument.ToString	());
	}
}
Permalink

In the ItemDataBound Event write following code
VB.NET


Dim i As Integer = 0
If e.Item.ItemType = ListItemType.Header Then
	For i = 0 To e.Item.Cells.Count  -1
                	Me.ListBox1.Items.Add(e.Item.Cells(i).Text)
            	Next
End If

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));
	}
} 
Permalink

<asp:Label id='Label1' runat='server'>Label</asp:Label>
<asp:DataGrid id='DataGrid1' OnSelectedIndexChanged=SelectedIndexChg AutoGenerateColumns='False' runat='server'>
<Columns>
	<asp:ButtonColumn Text ='Select' ButtonType =PushButton CommandName ='Select' ></asp:ButtonColumn>
	<asp:BoundColumn Headertext='ProductId' DataField='Productid'></asp:BoundColumn>
	<asp:BoundColumn Headertext='ProductName' DataField='ProductName'></asp:BoundColumn>
</Columns>
</asp:DataGrid>

VB.NET


Protected Sub SelectedIndexChg(ByVal sender As Object, ByVal e As System.EventArgs)
	Label1.Text = DataGrid1.SelectedItem.Cells(1).Text & DataGrid1.SelectedItem.Cells(2).Text  
End Sub

C#


protected void SelectedIndexChg(object sender, System.EventArgs e)
{
        Label1.Text = DataGrid1.SelectedItem.Cells[1].Text + DataGrid1.SelectedItem.Cells[2].Text ;
}
Permalink

<asp:DataGrid id='DataGrid1' AutoGenerateColumns='False' runat='server'>
<Columns>
	<asp:HyperLinkColumn HeaderText='ID' DataNavigateUrlField='ID' 
	DataNavigateUrlFormatString='page2.aspx?id={0}' 
	DataTextField='ID'></asp:HyperLinkColumn>
	</Columns>
</asp:DataGrid>

Permalink

<asp:DataGrid id='DataGrid1' AutoGenerateColumns=False  runat='server'></asp:DataGrid>

VB.NET

Create class


Public Class newLabelColumn
    Implements ITemplate

Public Sub New()
End Sub ’New

’Add constructor stuff here
Public Sub InstantiateIn(ByVal container As Control) Implements System.Web.UI.ITemplate.InstantiateIn
	Dim label1 As New Label
        	AddHandler label1.DataBinding, AddressOf Me.BindLabelColumn
        	container.Controls.Add(label1)
End Sub ’InstantiateIn

Public Sub BindLabelColumn(ByVal sender As Object, ByVal e As EventArgs)
        	Dim lbl As Label = CType(sender, Label)
        	Dim container As DataGridItem = CType(lbl.NamingContainer, DataGridItem)
        	Dim strVals As [String] = Convert.ToString(DataBinder.Eval(CType(container, DataGridItem).DataItem, 'LastName')) + ', ' + Convert.ToString(DataBinder.Eval(CType(container, DataGridItem).DataItem, 'FirstName'))
        	lbl.Text = strVals
End Sub ’BindLabelColumn
End Class ’newLabelColumn

’Fill the Dataset
Dim objtc As New TemplateColumn
objtc.HeaderText = 'Full Name'
objtc.ItemTemplate = New newLabelColumn
DataGrid1.Columns.Add(objtc)
DataGrid1.DataSource = ds
DataGrid1.DataBind()

C#

Create class


public class newLabelColumn : ITemplate
{
	public newLabelColumn()
	{
		//Add constructor stuff here
	}
	public void InstantiateIn(Control container)
	{
		Label label1 = new Label();
		label1.DataBinding += new EventHandler(this.BindLabelColumn);
		container.Controls.Add(label1);
	}
	public void BindLabelColumn(object sender, EventArgs e)
	{
		Label lbl = (Label)sender;
		DataGridItem container = (DataGridItem)lbl.NamingContainer ;
		String strVals 	=
		Convert.ToString(DataBinder.Eval(((DataGridItem)container).DataItem, 	'LastName')) + ', '
		+
		Convert.ToString(DataBinder.Eval(((DataGridItem)container).DataItem, 'FirstName')) ;
		lbl.Text = strVals;
	} 
}


//Fill the DataSet
TemplateColumn objtc = new TemplateColumn();
objtc.HeaderText = 'Full Name';
objtc.ItemTemplate = new newLabelColumn();
DataGrid1.Columns.Add(objtc); 
DataGrid1.DataSource =ds;
DataGrid1.DataBind();
Permalink

<asp:DataGrid id='DataGrid1' AutoGenerateColumns='False' runat='server'>
	<Columns>
		<asp:TemplateColumn HeaderText='FirstName'>
			<ItemTemplate>
				<input type='radio' name='optSelectedName' 
value=<%#DataBinder.Eval(Container.DataItem, 'FirstName') %> 
onclick='javascript:txtFname.value = this.value;'><%#DataBinder.Eval(Container.DataItem, 'FirstName') %>
			 <br>
			</ItemTemplate>
		</asp:TemplateColumn>
	</Columns>
</asp:DataGrid>
<asp:Button id='Button1' style='Z-INDEX: 101; LEFT: 154px; POSITION: absolute; TOP: 103px' runat='server'
			Text='Button'></asp:Button>
<div style='VISIBILITY: hidden'>
	<asp:TextBox ID='txtFname' Runat='server' />
</div>

VB.NET


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
	’Bind the Datagrid with dataSet
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  	Response.Write('You have selected :' & txtFname.Text)
End Sub

C#


private void Page_Load(object sender, System.EventArgs e)
{
	//Bind the datagrid to dataset
}
private void Button1_Click(object sender, System.EventArgs e)
{
	        Response.Write('You have selected :' + txtFname.Text);
}
Permalink

<asp:DataGrid id='DataGrid1' OnSortCommand ='SortDataGrid' runat='server' AllowSorting='True' EnableViewState='False'></asp:DataGrid>

VB.NET


Protected SQLStmt As String = 'Select * from Products  '
Dim myconnection As SqlConnection
Dim myda As SqlDataAdapter
Dim ds As DataSet
Dim strConn As String
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
	’Put user code to initialize the page here
	binddata()
End Sub

Sub 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()
End Sub

Protected Sub SortDataGrid(ByVal source As Object, 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'
        	End If
        	SQLStmt = SQLStmt & ' ORDER BY ' & e.SortExpression & ' ' & ViewState('SortOrder')
	binddata()
End Sub

C#


SqlConnection myconnection ; 
SqlDataAdapter myda ; 
DataSet ds ; 
String strConn ;
string SQLStmt= 'Select * from Products  ';
private void Page_Load(object sender, System.EventArgs e)
{
	// Put user code to initialize the page here
	binddata();
}

void 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();
}

protected void SortDataGrid(object source   , System.Web.UI.WebControls.DataGridSortCommandEventArgs   e  )  
{
	if (ViewState['SortOrder'] ==null)
	{
		ViewState['SortOrder'] = ' ASC';
	}
	else if (ViewState['SortOrder'].ToString () == ' ASC' )
	{
		ViewState['SortOrder'] = ' DESC';
	}
	else
	{
		ViewState['SortOrder'] = ' ASC';
	}
	SQLStmt = SQLStmt + ' ORDER BY ' + e.SortExpression.ToString () + ' ' + ViewState['SortOrder'];
	binddata();
}
Permalink

<asp:DataGrid id='DataGrid1' OnItemDataBound ='ItemDB' DataKeyField ='ProductId' runat='server'></asp:DataGrid>

VB.NET


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        	’Put user code to initialize the page here
        	If Not Page.IsPostBack Then
            		’Bind the dataGrid to DataView
        	End If
End Sub

Protected Sub ItemDB(ByVal sender As Object, 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 As String
        	For Each 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’)')
            		End If
        	Next
End Sub

C#


private void Page_Load(object sender, System.EventArgs e)
{
	// Put user code to initialize the page here
	if(!Page.IsPostBack )
	{
		//Bind Datagrid to DataView
	}
}

protected void ItemDB(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’)');
		}
	}
}
Permalink

<asp:DataGrid id='DataGrid1' OnItemDataBound='ItemDB' ShowFooter =true runat='server'></asp:DataGrid>

VB.NET


Dim UnitPrice As Double
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
       	’Put user code to initialize the page here
        	’Bind the Data to datagrid
End Sub

Protected Sub UPTotal(ByVal _unitprice As Double)
       	UnitPrice += _unitprice
End Sub ’UPTotal

Public Sub ItemDB(ByVal sender As Object, 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))
        	Else
            		If e.Item.ItemType = ListItemType.Footer Then
                		e.Item.Cells(0).Text = '  Total '
                		e.Item.Cells(1).Text = UnitPrice.ToString()
            		End If
        	End If
End Sub ’ItemDB 

C#


double UnitPrice;
private void Page_Load(object sender, System.EventArgs e)
{
	// Put user code to initialize the page here
	if(!Page.IsPostBack )
	{
		//Bind the DataGrid
	}
}
	
protected void UPTotal(double _unitprice)
{  
	UnitPrice  += _unitprice;
}

public void ItemDB(object sender, DataGridItemEventArgs e)
{
	if ((e.Item.ItemType == ListItemType.Item) ||( e.Item.ItemType == ListItemType.AlternatingItem))
	{
		UPTotal(Double.Parse ( e.Item.Cells[1].Text ));
	}
	else if (e.Item.ItemType ==ListItemType.Footer )
	{
		e.Item.Cells [0].Text ='  Total ';
		e.Item.Cells[1].Text =UnitPrice.ToString ();
	}	 
}
Permalink

<asp:Label id='Label1' runat='server'>Label</asp:Label>
<asp:DataGrid id='DataGrid1' OnSelectedIndexChanged='SelectedIndexChg' AutoGenerateColumns='False' runat='server'>
<Columns>
	<asp:ButtonColumn Text='Select' ButtonType='PushButton' CommandName='Select'></asp:ButtonColumn>
	<asp:TemplateColumn HeaderText='ProductId'>
		<ItemTemplate>
			<%#DataBinder.Eval(Container.DataItem , 'Productid')%>
		</ItemTemplate>
	</asp:TemplateColumn>
	<asp:TemplateColumn HeaderText='ProductName'>
		<ItemTemplate>
			<%#DataBinder.Eval(Container.DataItem , 'ProductName')%>
		</ItemTemplate>
	</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

VB.NET


Protected Sub SelectedIndexChg(ByVal sender As Object, ByVal e As System.EventArgs)
        Label1.Text = CType(DataGrid1.SelectedItem.Cells(1).Controls(0), DataBoundLiteralControl).Text & CType(DataGrid1.SelectedItem.Cells(2).Controls(0), DataBoundLiteralControl).Text
    End Sub

C#


protected void SelectedIndexChg(object sender, System.EventArgs e)
{
        Label1.Text =  ((DataBoundLiteralControl)DataGrid1.SelectedItem.Cells[1].Controls[0]).Text + ((DataBoundLiteralControl)DataGrid1.SelectedItem.Cells[2].Controls[0]).Text;
}
Permalink

<asp:Label id='Label1' runat='server'>Label</asp:Label>
<asp:DataGrid id='DataGrid1' OnSelectedIndexChanged='SelectedIndexChg' AutoGenerateColumns='False' runat='server'>
<Columns>
	<asp:ButtonColumn Text='Select' ButtonType='PushButton' CommandName='Select'></asp:ButtonColumn>
	<asp:TemplateColumn HeaderText='ProductId'>
		<ItemTemplate>
			<asp:Label text=<%#DataBinder.Eval(Container.DataItem , 'Productid')%> ID='lbl1' Runat=server ></asp:Label>
		</ItemTemplate>
	</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

VB.NET


Protected Sub SelectedIndexChg(ByVal sender As Object, ByVal e As System.EventArgs)
        Label1.Text = CType(DataGrid1.SelectedItem.FindControl('lbl1'), Label).Text
    End Sub

C#


protected void SelectedIndexChg(object sender, System.EventArgs e)
{
        Label1.Text =  ((Label)DataGrid1.SelectedItem.FindControl ('lbl1')).Text ;
}
Permalink

<asp:DataGrid id='DataGrid1'  runat='server'></asp:DataGrid>

VB.NET


’Fill the DataSet ds with data from database
Dim 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();
Permalink

<asp:DataGrid id='DataGrid1' runat='server'></asp:DataGrid>

VB.NET


Dim strArray As String() = {'Tom', 'Jerry', 'Harry', 'Mickey'}
DataGrid1.DataSource = strArray
DataGrid1.DataBind()

C#


string[] strArray  = {'Tom','Jerry', 'Harry', 'Mickey'};
DataGrid1.DataSource = strArray;
DataGrid1.DataBind();
Permalink

<asp:DataGrid id='DataGrid1' runat='server'>
	<Columns>
	<asp:TemplateColumn HeaderText='Boolean Value'>
		<ItemTemplate>
		<asp:CheckBox id=CheckBox1 runat='server' onCheckedChanged='chkChanged' Checked=’<%# DataBinder.Eval(Container.DataItem, 'Discontinued') %>’ AutoPostBack='True'>
		</asp:CheckBox>
		</ItemTemplate>
	</asp:TemplateColumn>
	</Columns>
</asp:DataGrid>

VB.NET


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
       	 ’Put user code to initialize the page here
        	If Not IsPostBack Then
           		’Populate the datagrid
        	End If
End Sub

protected Sub chkChanged(ByVal sender As Object, ByVal e As System.EventArgs)
	Response.Write('CheckChanged Event')
End Sub

C#


private void Page_Load(object sender, System.EventArgs e)
{
	// Put user code to initialize the page here
	if (!Page.IsPostBack )
	{
		DataGrid1.DataSource =BindDataClass.BindData ();
		DataGrid1.DataBind ();
	}
}

protected void chkChanged(object sender , System.EventArgs   e  )
{
	Response.Write('CheckChanged Event');
}
Permalink

<asp:DataGrid id='DataGrid1' runat='server' AutoGenerateColumns='False'>
<Columns>
<asp:TemplateColumn HeaderText='ProductName'>
  	  <ItemTemplate>
		    <%#DataBinder.Eval(Container.DataItem, 'ProductName').ToString()%>
	  </ItemTemplate>
	  <EditItemTemplate>
		    <asp:Textbox runat='server' width='450' maxlength='450'/>
	  </EditItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

Permalink

<asp:DataGrid id='DataGrid1' onItemDataBound='ItemDB' runat='server'></asp:DataGrid>

VB.NET


protected Sub ItemDB (ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)
             e.Item.Cells(0).Visible = False
End Sub

C#


protected void ItemDB (object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
            e.Item.Cells[0].Visible = false;
}
Permalink

<asp:DataGrid id='DataGrid1' AutoGenerateColumns='False' runat='server'>
	<Columns>
	<asp:TemplateColumn HeaderText='Link'>
		<ItemTemplate>
			<asp:HyperLink Runat =server NavigateUrl =’<%#GetURL(DataBinder.Eval(Container.DataItem, 'RegionDescription').ToString())%>’ ID='Hyperlink1'>
				<%#DataBinder.Eval(Container.DataItem, 'RegionDescription')%>
			</asp:HyperLink>
		</ItemTemplate>
	</asp:TemplateColumn>
	</Columns>
</asp:DataGrid>

VB.NET


Protected Function GetURL(ByVal fldval As String) As String
	If fldval.IndexOf('http://', 0, fldval.Length) = 0 Then
	            Return fldval
	Else
	            Return 'http://' + fldval
	End If
End Function ’GetURL

C#


protected	string GetURL (string fldval   )  
{
	if  (fldval.IndexOf ( 'http://' , 0, fldval.Length ) ==0)
	{
		return fldval;
	}
	else
	{
		return 'http://' + fldval;
	} 
}
Permalink

<asp:DataGrid id='DataGrid1' OnItemCommand='ItemCmd' runat='server'>
	<Columns>
		<asp:ButtonColumn DataTextField='ProductID' CommandName='Show' HeaderText='Productid' ButtonType='LinkButton'
		Text='Click'></asp:ButtonColumn>
	</Columns>
</asp:DataGrid>

VB.NET


Protected Sub ItemCmd(source As Object, e As System.Web.UI.WebControls.DataGridCommandEventArgs)
   If e.CommandName.ToString() = 'Show' Then
      Response.Write(e.Item.Cells(5).Text)
   End If
End Sub ’ItemCmd

C#


protected void ItemCmd(Object source, System.Web.UI.WebControls.DataGridCommandEventArgs e   ) 
{ 
	if (e.CommandName.ToString () == 'Show')
	{
		Response.Write(  e.Item.Cells[5].Text  );
	}
}
Permalink

<asp:datagrid id='DataGrid1' runat='server' DataKeyField='Regionid' OnDeleteCommand='DataGrid1_Delete'
	 OnEditCommand='DataGrid1_Edit' OnCancelCommand='DataGrid1_Cancel'>
<Columns>
	<asp:ButtonColumn Text='Delete' CommandName='Delete' />
</Columns>
</asp:datagrid>
<asp:Label id='lblError' style='Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 160px' runat='server'
	Visible='False' ForeColor='Red'></asp:Label>

VB.NET


Dim mycn As SqlConnection
Dim myda As SqlDataAdapter
Dim ds As DataSet
Dim strConn, strSQL As String

Private Sub Page_Load(sender As Object, e As System.EventArgs)
	strConn = 'server=localhost;uid=sa;database=northwind;pwd=;'
		If Not Page.IsPostBack Then
			BindGrid()
		End If
End Sub ’Page_Load

Sub 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()
End Sub ’BindGrid

Public Sub DataGrid1_Cancel(sender As [Object], e As DataGridCommandEventArgs)
	DataGrid1.EditItemIndex = - 1
	BindGrid()
End Sub ’DataGrid1_Cancel

Public Sub DataGrid1_Edit(sender As [Object], e As DataGridCommandEventArgs)
	DataGrid1.EditItemIndex = CInt(e.Item.ItemIndex)
	BindGrid()
End Sub ’DataGrid1_Edit

Public Sub DataGrid1_Delete(sender As [Object], e As DataGridCommandEventArgs)
	Dim orderid As Integer = CInt(DataGrid1.DataKeys(CInt(e.Item.ItemIndex)))
	Dim deleteCmd As [String] = 'DELETE from Region where Regionid = @Regionid  '
	Dim cn As New SqlConnection(strConn)
	Dim myCommand As New 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'
	End Try
	myCommand.Connection.Close()
	BindGrid()
End Sub ’DataGrid1_Delete

C#


SqlConnection mycn;
SqlDataAdapter myda;
DataSet ds;
string strConn,strSQL;

private void Page_Load(object sender, System.EventArgs e)
{
	strConn ='server=localhost;uid=sa;database=northwind;pwd=;';
	if (!Page.IsPostBack )
	{
		BindGrid();
	}
}

void 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 (); 
}

public void DataGrid1_Cancel(Object sender, DataGridCommandEventArgs e)
{
	DataGrid1.EditItemIndex = -1;
	BindGrid();
}

public void DataGrid1_Edit(Object sender, DataGridCommandEventArgs e)
{
	DataGrid1.EditItemIndex = (int)e.Item.ItemIndex;			 
	BindGrid(); 
}

public void DataGrid1_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();
}
Permalink

<asp:datagrid id='DataGrid1' runat='server' DataKeyField='OrderID'  
	OnUpdateCommand='DataGrid1_Update' OnEditCommand='DataGrid1_Edit' OnCancelCommand='DataGrid1_Cancel'>
<Columns>
	<asp:EditCommandColumn EditText='Edit' CancelText='Cancel' UpdateText='Update' />
</Columns>
</asp:datagrid>
<asp:Label id='lblError' style='Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 160px' runat='server'
	Visible='False' ForeColor='Red'></asp:Label>

VB.NET


Dim mycn As SqlConnection
Dim myda As SqlDataAdapter
Dim ds As DataSet
Dim strConn, strSQL As String

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
	strConn = 'server=localhost;uid=sa;database=northwind;pwd=;'
	If Not Page.IsPostBack Then
	            BindGrid()
	End If
End Sub ’Page_Load

Sub BindGrid()
  	mycn = New SqlConnection(strConn)
	strSQL = 'Select * from [Order Details] where orderid=10249'
	myda = New SqlDataAdapter(strSQL, mycn)
	ds = New DataSet
	myda.Fill(ds, 'Table')
	DataGrid1.DataSource = ds
	DataGrid1.DataBind()
End Sub ’BindGrid

Public Sub DataGrid1_Cancel(ByVal sender As [Object], ByVal e As DataGridCommandEventArgs)
	DataGrid1.EditItemIndex = -1
	BindGrid()
End Sub ’DataGrid1_Cancel

Public Sub DataGrid1_Edit(ByVal sender As [Object], ByVal e As DataGridCommandEventArgs)
	DataGrid1.EditItemIndex = CInt(e.Item.ItemIndex)
	BindGrid()
End Sub ’DataGrid1_Edit

Public Sub DataGrid1_Update(ByVal sender As [Object], ByVal e As DataGridCommandEventArgs)
	Dim unitprice As String = CType(e.Item.Cells(3).Controls(0), TextBox).Text
	Dim quantity As String = CType(e.Item.Cells(4).Controls(0), TextBox).Text
	Dim discount As String = CType(e.Item.Cells(5).Controls(0), TextBox).Text
	Dim orderid As Integer = CInt(DataGrid1.DataKeys(CInt(e.Item.ItemIndex)))
	Dim productid As String = CType(e.Item.Cells(2).Controls(0), TextBox).Text

	Try
		Dim updateCmd As String = 'UPDATE [Order Details] SET  UnitPrice = @UnitPrice,' + 'Quantity = @Quantity, Discount = @Discount  where OrderId =@OrderId  and ProductId=@ProductId'
	            Dim cn As New SqlConnection(strConn)
	            Dim myCommand As New SqlCommand(updateCmd, cn)
	            myCommand.Parameters.Add(New SqlParameter('@UnitPrice', Convert.ToDecimal(unitprice)))
	            myCommand.Parameters.Add(New SqlParameter('@Quantity', Convert.ToInt16(quantity)))
	            myCommand.Parameters.Add(New SqlParameter('@Discount', Convert.ToInt16(discount)))
	            myCommand.Parameters.Add(New SqlParameter('@OrderId', orderid))
	            myCommand.Parameters.Add(New SqlParameter('@ProductId', Convert.ToInt16(productid)))
	            cn.Open()
	            myCommand.ExecuteNonQuery()
	            DataGrid1.EditItemIndex = -1
	            BindGrid()
	Catch ex As Exception
	            lblError.Visible = True
	            lblError.Text = ex.Message
	End Try
End Sub ’DataGrid1_Update

C#


SqlConnection mycn;
SqlDataAdapter myda;
DataSet ds;
string strConn,strSQL;

private void Page_Load(object sender, System.EventArgs e)
{
	strConn ='server=localhost;uid=sa;database=northwind;pwd=;';
	if (!Page.IsPostBack )
	{
		BindGrid();
	}
}

void BindGrid()
{
	mycn = new SqlConnection(strConn);
	strSQL = 'Select * from [Order Details] where orderid=10249'  ;
	myda = new SqlDataAdapter (strSQL, mycn);
	ds= new DataSet ();
	myda.Fill (ds,'Table');
	DataGrid1.DataSource =ds;
	DataGrid1.DataBind (); 
}

public void DataGrid1_Cancel(Object sender, DataGridCommandEventArgs e)
{
	DataGrid1.EditItemIndex = -1;
	BindGrid();
}

public void DataGrid1_Edit(Object sender, DataGridCommandEventArgs e)
{
	DataGrid1.EditItemIndex = (int)e.Item.ItemIndex;			 
	BindGrid(); 
}

public void DataGrid1_Update(Object sender, DataGridCommandEventArgs e)
{
	string unitprice =((TextBox)e.Item.Cells[3].Controls[0] ).Text  ;
	string quantity =((TextBox)e.Item.Cells[4].Controls[0] ).Text  ;
	string discount=((TextBox)e.Item.Cells[5].Controls[0] ).Text  ;
	int orderid = (int)DataGrid1.DataKeys[(int)e.Item.ItemIndex];
	string productid= ((TextBox)e.Item.Cells[2].Controls[0] ).Text  ;
	try
	{
		string updateCmd = 'UPDATE [Order Details] SET  UnitPrice = @UnitPrice,'
		+ 'Quantity = @Quantity, Discount = @Discount  where OrderId =@OrderId  and ProductId=@ProductId';
		SqlConnection cn = new SqlConnection (strConn);
		SqlCommand myCommand = new SqlCommand(updateCmd, cn);
		myCommand.Parameters.Add(new SqlParameter('@UnitPrice', Convert.ToDecimal(unitprice )));
		myCommand.Parameters.Add(new SqlParameter('@Quantity', Convert.ToInt16 (quantity  ) ));
		myCommand.Parameters.Add(new SqlParameter('@Discount', Convert.ToInt16 ( discount   )));
		myCommand.Parameters.Add(new SqlParameter('@OrderId',  orderid));
		myCommand.Parameters.Add(new SqlParameter('@ProductId', Convert.ToInt16 ( productid)));
		cn.Open ();
		myCommand.ExecuteNonQuery ();
		DataGrid1.EditItemIndex = -1;
		BindGrid();
	}
	catch(Exception ex)
	{
		lblError.Visible =true;
		lblError.Text =(ex.Message );
	}
}
Permalink

<asp:DataGrid  id='DataGrid1' runat='server'></asp:DataGrid>

VB.NET


Dim cn As SqlConnection
Dim da As SqlDataAdapter
Dim ds As DataSet

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.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()
End Sub ’Page_Load

Public Function GoDoReShape(ByVal ds As DataSet) As DataSet
	Dim NewDs As 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')

	Dim dr As DataRow
	For Each dr In ds.Tables(0).Rows
		Dim dcol As System.Data.DataColumn
	                For Each dcol In ds.Tables(0).Columns
		                ’Declare Array
		                Dim MyArray As String() = {dcol.ColumnName.ToString(), dr(dcol.ColumnName.ToString()).ToString()}
		                NewDs.Tables(0).Rows.Add(MyArray)
		Next 
	Next 
	Return NewDs
End Function ’GoDoReShape

C#


SqlConnection cn ;
SqlDataAdapter da;
DataSet ds;

private void Page_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 Array
			string[] MyArray={dcol.ColumnName.ToString(),dr[dcol.ColumnName.ToString()].ToString()};
			NewDs.Tables[0].Rows.Add(MyArray);
		}
	}
	return NewDs;								
}

Permalink

<asp:DataGrid id='DataGrid1' runat='server'>
<Columns>
<asp:TemplateColumn HeaderText ='Product Information' >
<ItemTemplate >
<asp:Button CommandName='Status' Text ='Status' Runat =server  
	Enabled =<%#CheckStatus(Convert.ToBoolean(DataBinder.Eval(Container.DataItem,'Discontinued')))%> ID='Button1' >
</asp:Button>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

VB.NET


Protected Function CheckStatus(ByVal prdStatus As Boolean) As Boolean
	If prdStatus = False Then
		Return True
	Else
		Return False
	End If
End Function

C#


protected bool CheckStatus(bool prdStatus)
{
	//If the Discontinued field is '0'
	if (prdStatus==false)
	{
		return true;
	}
	//If the Discontinued field is '1'
	else
	{
		return false;
	}
}
Permalink

Yes. Use a TemplateColumn in a DataGrid


<asp:DataGrid id='DataGrid1' runat=server AutoGenerateColumns=False>
	<Columns>
		<asp:TemplateColumn HeaderText='Field'>
			<ItemTemplate>
				<%#DataBinder.Eval(Container.DataItem, 'Field1').ToString()%> - <%#DataBinder.Eval(Container.DataItem, 'Field2').ToString()%>
			</ItemTemplate>
		</asp:TemplateColumn>
	</Columns>
</asp:DataGrid>
Permalink

<asp:DataGrid id='DataGrid1' AutoGenerateColumns=False OnCancelCommand ='CancelCmd' OnEditCommand ='EditCmd' 
	OnUpdateCommand ='UpdateCmd' DataKeyField='Employeeid'  runat='server'>
<Columns>
	<asp:TemplateColumn HeaderText ='Employee Information'>
	<ItemTemplate >
		<asp:label ID='lblLastName' Runat=server text=<%#DataBinder.Eval(Container.DataItem, 'Lastname')%>></asp:Label> 
,		<asp:label ID='lblFirstName' Runat=server text=<%#DataBinder.Eval(Container.DataItem, 'Firstname')%>></asp:Label> 
		<br>
		<asp:label ID='lblTitle' Runat=server text=<%#DataBinder.Eval(Container.DataItem, 'Title')%>> 
	</ItemTemplate>
	<EditItemTemplate >
		<asp:TextBox runat=server ID='txtLastName' Text=<%#DataBinder.Eval(Container.DataItem, 'lastname')%>></asp:TextBox>
		<asp:RequiredFieldValidator  id='rqdfldLastName' Display ='Static' Runat =server ErrorMessage ='*' 
			ControlToValidate ='txtLastName'>
		<asp:TextBox runat=server ID='txtFirstName' text=<%#DataBinder.Eval(Container.DataItem, 'Firstname')%>></asp:TextBox>
		<asp:RequiredFieldValidator  id='rqdfldFirstName' Display ='Static' Runat =server ErrorMessage ='*' 
			ControlToValidate ='txtFirstName'>
		<asp:TextBox runat=server ID='txtTitle' Text=<%#DataBinder.Eval(Container.DataItem, 'title')%>></asp:TextBox>
	</EditItemTemplate>
	</asp:TemplateColumn>
<asp:EditCommandColumn ButtonType='PushButton' CancelText='Cancel' EditText='Edit' UpdateText='Update'></asp:EditCommandColumn>
</Columns>
</asp:DataGrid>

VB.NET


Dim sqlStmt As String
Dim conString As String
Dim cn As SqlConnection
Dim cmd As SqlCommand
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        	’ Put user code to initialize the page here
        	If Not Page.IsPostBack Then
            		BindGrid()
        	End If
End Sub ’Page_Load

Sub BindGrid()
        	’Bind the Datagrid with dataSet
End Sub ’BindGrid


Protected Sub EditCmd(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)
        	DataGrid1.EditItemIndex = CInt(e.Item.ItemIndex)
        	BindGrid()
End Sub ’EditCmd

Public Sub CancelCmd(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)
        	DataGrid1.EditItemIndex = -1
        	BindGrid()
End Sub ’CancelCmd

Protected Sub UpdateCmd(ByVal sender As Object, 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 As String
            		LastName = CType(e.Item.FindControl('txtLastName'), TextBox).Text
            		FirstName = CType(e.Item.FindControl('txtFirstName'), TextBox).Text
            		Title = CType(e.Item.FindControl('txtTitle'), TextBox).Text
            		Dim EmployeeId As Integer = 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 = -1
	                Catch ex As Exception
		               Response.Write(ex.Message.ToString())
		End Try
		BindGrid()
	End If
End Sub ’UpdateCmd

C#


private void Page_Load(object sender, System.EventArgs e)
{
	// Put user code to initialize the page here
	if (!Page.IsPostBack )
	{
		BindGrid();
	}
}

void BindGrid()
{
	//Bind the DataGrid with dataset
}

protected void EditCmd(object sender, DataGridCommandEventArgs e)
{
	DataGrid1.EditItemIndex = (int)e.Item.ItemIndex;
	BindGrid();
}

public void  CancelCmd(object sender, DataGridCommandEventArgs e)
{
	 DataGrid1.EditItemIndex = -1;
	BindGrid();
}

string sqlStmt;
string conString;
SqlConnection cn;
SqlCommand cmd;
protected void UpdateCmd(object sender, DataGridCommandEventArgs e)
{
	if (Page.IsValid)
	{
	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);
	string LastName , FirstName , Title;
	LastName = ((TextBox )e.Item.FindControl ('txtLastName')).Text ;
	FirstName = ((TextBox )e.Item.FindControl ('txtFirstName')).Text ;
	Title  = ((TextBox )e.Item.FindControl ('txtTitle')).Text ;
	int EmployeeId =(int) DataGrid1.DataKeys[(int)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 = -1;
	}
	catch(Exception ex)
	{
		Response.Write (ex.Message.ToString () );
	}
	BindGrid();
	}
}

Permalink

<asp:DataGrid id='DataGrid1' OnItemDataBound ='ItemDB' AllowSorting='True' OnSortCommand='SortData' runat='server'></asp:DataGrid>

VB.NET


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ’Put user code to initialize the page here
        If Not Page.IsPostBack Then
            BindDataGrid('ProductId')
        End If
End Sub

Protected Sub SortData(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs)
        BindDataGrid(e.SortExpression.ToString())
End Sub

Sub BindDataGrid(ByVal sortfield As String)
        ViewState('SortExpression') = sortfield
        ’Fill the DataSet
        Dim dv As DataView = ds.Tables(0).DefaultView
        dv.Sort = sortfield
        DataGrid1.DataSource = dv
        DataGrid1.DataBind()
End Sub

Protected Sub ItemDB(ByVal sender As Object, 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 Then
            If ViewState('SortExpression') <> '' Then
                e.Item.Cells(dc.IndexOf(dc(ViewState('SortExpression')))).BackColor = Color.BlueViolet
                e.Item.Cells(dc.IndexOf(dc(ViewState('SortExpression')))).ForeColor = Color.AntiqueWhite
            End If
        End If
End Sub

C#


private void Page_Load(object sender, System.EventArgs e)
{
	// Put user code to initialize the page here
	if(! Page.IsPostBack  )
	{
		BindDataGrid('ProductId');
	}
}

protected void SortData(Object source,  System.Web.UI.WebControls.DataGridSortCommandEventArgs  e )
{
	BindDataGrid(e.SortExpression.ToString());
}

void BindDataGrid(string sortfield)
{
	ViewState['SortExpression'] = sortfield;
	//Fill the dataset
	DataView dv    = ds.Tables[0].DefaultView;
	dv.Sort = sortfield;
	DataGrid1.DataSource = dv;
	DataGrid1.DataBind();
}

protected void ItemDB(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;
		}
	}
}
Permalink

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

<asp:DataGrid id='DataGrid1' AutoGenerateColumns='False' DataKeyField='ProductID' OnUpdateCommand='DataGrid1_Update'
	OnEditCommand='DataGrid1_Edit' OnCancelCommand='DataGrid1_Cancel' runat='server'>
<Columns>
<asp:TemplateColumn HeaderText='Discontinued'>
	<ItemTemplate>
	<asp:Label ID='lblDiscontinued' Text=’<%#ShowVal(Convert.ToBoolean( DataBinder.Eval(Container.DataItem, 'Discontinued').ToString()) )%>’ Runat='server' />
	</ItemTemplate>

	<EditItemTemplate>
	<asp:Label runat='server' id='lblProductID' Visible='False' Text=’<%# DataBinder.Eval(Container.DataItem, 'ProductId') %>’/>
	<asp:Label ID='lblEditDiscontinued' Text=’<%#ShowVal(Convert.ToBoolean(DataBinder.Eval(Container.DataItem, 'Discontinued').ToString() ))%>’ Runat='server' />
	<asp:DropDownList id='ddlDiscontinued' DataSource='<%# BindTheDiscontinued() %>' OnPreRender='SetDropDownIndex' DataTextField='Discontinued' DataValueField='Discontinued' runat='server' />
	</EditItemTemplate>
</asp:TemplateColumn>

<asp:EditCommandColumn EditText='Edit' CancelText='Cancel' UpdateText='Update' ItemStyle-Width='100px' HeaderText='Commands' />
</Columns>
</asp:DataGrid>

Code Behind
VB.NET


Dim strDiscontinued As String
Dim obj As GetData
Dim strSql As String
Dim strConn As String
Dim ds As DataSet
Dim dr As SqlDataReader

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
’ Put user code to initialize the page here
strConn = 'server=localhost;uid=sa;pwd=;database=northwind'
If Not Page.IsPostBack Then
	BindGrid()
End If
End Sub ’Page_Load

’To Bind the DataGrid
Sub BindGrid()
	obj = New GetData
	strSql = 'Select productid, discontinued from Products'
	ds = obj.GetDataFromTable(strSql, strConn)
	DataGrid1.DataSource = ds
	DataGrid1.DataBind()
End Sub ’BindGrid

’To display Yes/No for True/False
Protected Function ShowVal(ByVal blnval As Boolean) As String
	If blnval = True Then
		Return 'Yes'
	Else
		Return 'No'
	End If
End Function ’ShowVal

’Bind the Data to the dropdownlist in the EditTemplate
Protected Function 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
End Function ’BindTheDiscontinued

’Set the Text of the Dropdownlist to the field value in Database
Protected Sub 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))
End Sub ’SetDropDownIndex

’For Edit Update Cancel
Public Sub 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()
End Sub ’DataGrid1_Edit

Public Sub 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()
End Sub ’DataGrid1_Update

Public Sub DataGrid1_Cancel(ByVal sender As [Object], ByVal e As DataGridCommandEventArgs)
	DataGrid1.EditItemIndex = -1
	BindGrid()
End Sub ’DataGrid1_Cancel

’Functions used in Class GetData.cs
Dim mycn As SqlConnection
Dim myda As SqlDataAdapter
Dim mycmd As SqlCommand
Dim ds As DataSet
Dim strConn As String
Dim myReader As SqlDataReader

Public Function GetDataFromTable(ByVal strSQL As String, ByVal strConnString As String) 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
	Throw New Exception(ex.Message.ToString())
Finally
	mycn.Close()
End Try
End Function ’GetDataFromTable

Public Function GetSingleDataUsingReader(ByVal strSQL As String, ByVal strConnString As String) 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
	Throw New Exception(ex.Message.ToString())
Finally
	End Try ’mycn.Close ();
End Function ’GetSingleDataUsingReader 

C#


string strDiscontinued;
GetData obj;
string strSql;
string strConn;
DataSet ds;
SqlDataReader dr;
private void Page_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 DataGrid
void BindGrid()
{
	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/False
protected string ShowVal(bool blnval)
{
	if (blnval==true)
	{
		return 'Yes';
	} 
	else
	{
		return 'No';
	}
}

//Bind the Data to the dropdownlist in the EditTemplate
protected 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 Database

protected void SetDropDownIndex(Object sender ,System.EventArgs e   )
{
	DropDownList ed ; 
	ed = (DropDownList) sender;
	ed.SelectedIndex = ed.Items.IndexOf(ed.Items.FindByText(strDiscontinued));
}


//For Edit Update Cancel
public void DataGrid1_Edit(Object sender, DataGridCommandEventArgs e)
{
	strDiscontinued = ((Label )e.Item.FindControl('lblDiscontinued')).Text;
	DataGrid1.EditItemIndex = (int)e.Item.ItemIndex;    
	BindGrid(); 
}

public void DataGrid1_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();
}
public void DataGrid1_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)
{
	throw new 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)
{
	throw new Exception (ex.Message.ToString ());
}
finally
{
	//mycn.Close ();
}
}
Permalink

<asp:DataGrid id='DataGrid1' OnItemDataBound=ItemDB runat='server'></asp:DataGrid>

VB.NET


Private Sub Page_Load(sender As Object, e As System.EventArgs)
	’ Put user code to initialize the page here
	If Not Page.IsPostBack Then
		’Populate the DataGrid
	End If
End Sub ’Page_Load 

Protected Sub ItemDB(ByVal s As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)
	If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
		If e.Item.Cells(1).Text = ' ' Then
			e.Item.Cells(1).Text = 'No data'
		End If
	End If
End Sub ’ItemDB

C#


private void Page_Load(object sender, System.EventArgs e)
{
	// Put user code to initialize the page here
	if(!Page.IsPostBack )
	{
		//Populate the DataGrid
	}
}

protected void ItemDB (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';
		}
	}
}

In Cells[x]/Cells(x) x=> index number

Permalink

<asp:DataGrid id='DataGrid1' OnItemCommand ='ItemCmd' AutoGenerateColumns =False  runat='server'>
	<Columns>
		<asp:BoundColumn DataField='ProductID' HeaderText='ProductID'></asp:BoundColumn>
		<asp:BoundColumn DataField='Productname' HeaderText='Productname'></asp:BoundColumn>
		<asp:ButtonColumn DataTextField='Productid' CommandName='Show' HeaderText='Productid' ButtonType='PushButton'
			Text='Click'></asp:ButtonColumn>
	</Columns>
</asp:DataGrid>

VB.NET


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
	’Put user code to initialize the page here
	If Not Page.IsPostBack Then
	            ’Populate the DataGrid
	End If
End Sub

Protected Sub ItemCmd(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) 
	If e.CommandName = 'Show' Then
	            Response.Write(e.Item.Cells(1).Text)
	End If
End Sub

C#


private void Page_Load(object sender, System.EventArgs e)
{
	// Put user code to initialize the page here
	if (!Page.IsPostBack )
	{
		//Populate the DataGrid
	}
}

protected void ItemCmd(Object source   , System.Web.UI.WebControls.DataGridCommandEventArgs e   ) 
{ 
	if (e.CommandName.ToString () == 'Show')
	{
		Response.Write(e.Item.Cells[1].Text);
	}
}
 
Permalink

<asp:DataGrid id='DataGrid1' OnItemDataBound='ItemDB' runat='server'></asp:DataGrid>

VB.NET


Protected Sub ItemDB(ByVal s As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)
	If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
		Select Case Trim(e.Item.Cells(3).Text)
	                Case 'Sales Representative'
                	    e.Item.Cells(3).Text = 'SR'
	                Case 'Vice President, Sales'
                	    e.Item.Cells(3).Text = 'VP'
	                Case 'Sales Manager'
                	    e.Item.Cells(3).Text = 'SM'
	                Case 'Inside Sales Coordinator'
                	    e.Item.Cells(3).Text = 'ISC'
	                Case Else
                	    e.Item.Cells(3).Text = e.Item.Cells(3).Text
      		End Select
	end if
end sub

C#


protected void ItemDB (Object s  , System.Web.UI.WebControls.DataGridItemEventArgs e  )
{
	if ((e.Item.ItemType ==ListItemType.Item) ||(e.Item.ItemType ==ListItemType.AlternatingItem))
	{
		switch   ( e.Item.Cells[3].Text.Trim() ) 
		{
			case 'Sales Representative':
				e.Item.Cells[3].Text = 'SR';
				break;
			case 'Vice President, Sales':
				e.Item.Cells[3].Text = 'VP';
				break;
			case 'Sales Manager':
				e.Item.Cells[3].Text = 'SM';
				break;
			case 'Inside Sales Coordinator':
				e.Item.Cells[3].Text = 'ISC';
				break;
			default :
				e.Item.Cells[3].Text = e.Item.Cells[3].Text;
				break;
		}
	}
}
Permalink

<asp:DataGrid id='DataGrid1' AutoGenerateColumns='False' OnDeleteCommand ='DelCmd' OnItemCreated ='ItemCrt' DataKeyField='Employeeid'   runat='server'>
<Columns>
	<asp:ButtonColumn Text='Delete' ButtonType='PushButton' CommandName='Delete'></asp:ButtonColumn>
	<asp:BoundColumn DataField='firstname' HeaderText='First Name'></asp:BoundColumn>
</Columns>
</asp:DataGrid>

VB.NET


Dim sqlStmt As String
Dim conString As String
Dim cn As SqlConnection = Nothing
Dim da As SqlDataAdapter = Nothing
Dim ds As DataSet


Private Sub Page_Load(sender As Object, e As System.EventArgs)
   	conString = 'server=localhost;database=Northwind;uid=sa;pwd=;'
   	cn = New SqlConnection(conString)
   	If Not Page.IsPostBack Then
      		BindData()
   	End If
End Sub ’Page_Load

Sub BindData()
   	sqlStmt = 'select * from emp  '
   	ds = New DataSet()
   	da = New SqlDataAdapter(sqlStmt, cn)
   	da.Fill(ds, 't1')
   	DataGrid1.DataSource = ds
   	DataGrid1.DataBind()
End Sub ’BindData


Protected Sub ItemCrt(sender As Object, e As DataGridItemEventArgs)
   	Select Case 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’)')
            		Exit 
   	End Select
End Sub ’ItemCrt


Protected Sub DelCmd(sender As [Object], e As DataGridCommandEventArgs)
   	DeleteRow(Me.DataGrid1.DataKeys(e.Item.ItemIndex).ToString())
   	BindData()
End Sub ’DelCmd


Private Sub DeleteRow(empid As String)
   	Dim cmd As New SqlCommand('DELETE FROM Emp WHERE employeeid =' + empid, cn)
   	cn.Open()
   	cmd.ExecuteNonQuery()
   	cn.Close()
End Sub ’DeleteRow

C#


string  sqlStmt ; 
string  conString ; 
SqlConnection cn =null; 
SqlDataAdapter da =null; 
DataSet ds;

private void Page_Load(object sender, System.EventArgs e)
{
	conString = 'server=localhost;database=Northwind;uid=sa;pwd=;';
	cn = new SqlConnection(conString);
	if (!Page.IsPostBack )
	{
		BindData();
	}
}

void BindData()
{
	sqlStmt = 'select * from emp  ';
	ds= new DataSet ();
	da = new SqlDataAdapter (sqlStmt, cn);
	da.Fill (ds,'t1');
	DataGrid1.DataSource =ds;
	DataGrid1.DataBind ();
}

protected void ItemCrt(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;
		} 
	}	 
}

protected void  DelCmd(Object sender   , DataGridCommandEventArgs e   ) 
{
	DeleteRow (this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString());
	BindData();
}

private void DeleteRow(string empid)
{ 
	SqlCommand cmd = new SqlCommand('DELETE FROM Emp WHERE employeeid ='+ empid ,cn); 
	cn.Open(); 
	cmd.ExecuteNonQuery(); 
	cn.Close(); 
} 
Permalink

<script>
function  confirmmsg() 
{ 
	if (confirm('Do you want to delete record?')==true) 
		return true; 
	else 
		return false; 
}
</script>

<asp:DataGrid id='DataGrid1' AutoGenerateColumns='False' DataKeyField='Employeeid' OnItemCommand='ItemCmd' OnItemDataBound='ItemDB'  runat='server'>
<Columns>
	<asp:BoundColumn DataField='firstname' HeaderText='First Name'></asp:BoundColumn>
	<asp:TemplateColumn>
		<ItemTemplate>
			<asp:LinkButton id='btnDelete' runat='server' Text='Delete' CommandName='Delete' CausesValidation='false'></asp:LinkButton>
		</ItemTemplate>
	</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

VB.NET


Dim sqlStmt As String
Dim conString As String
Dim cn As SqlConnection = Nothing
Dim da As SqlDataAdapter = Nothing
Dim ds As DataSet

Private Sub Page_Load(sender As Object, e As System.EventArgs)
   	conString = 'server=localhost;database=Northwind;uid=sa;pwd=;'
   	cn = New SqlConnection(conString)
   	If Not Page.IsPostBack Then
     		BindData()
   	End If
End Sub ’Page_Load

Sub BindData()
   	sqlStmt = 'select * from emp  '
   	ds = New DataSet()
   	da = New SqlDataAdapter(sqlStmt, cn)
   	da.Fill(ds, 't1')
   	DataGrid1.DataSource = ds
   	DataGrid1.DataBind()
End Sub ’BindData

Protected Sub ItemDB(sender As Object, e As System.Web.UI.WebControls.DataGridItemEventArgs)
   	Select Case e.Item.ItemType
      		Case ListItemType.Item, ListItemType.AlternatingItem
            			Dim btn As LinkButton = CType(e.Item.FindControl('btnDelete'), LinkButton)
            			btn.Attributes.Add('onclick', 'return confirmmsg();')
            			Exit 
   	End Select
End Sub ’ItemDB

Protected Sub ItemCmd(sender As Object, e As System.Web.UI.WebControls.DataGridCommandEventArgs)
   	If e.CommandName = 'Delete' Then
      		Me.DeleteRow(Me.DataGrid1.DataKeys(e.Item.ItemIndex).ToString())
   	End If
   	BindData()
End Sub ’ItemCmd

Private Sub DeleteRow(empid As String)
   	Dim cmd As New SqlCommand('DELETE FROM Emp WHERE employeeid =' + empid, cn)
   	cn.Open()
   	cmd.ExecuteNonQuery()
   	cn.Close()
End Sub ’DeleteRow

C#


string  sqlStmt ; 
string  conString ; 
SqlConnection cn =null; 
SqlDataAdapter da =null; 
DataSet ds;
private void Page_Load(object sender, System.EventArgs e)
{
	conString = 'server=localhost;database=Northwind;uid=sa;pwd=;';
	cn = new SqlConnection(conString);
	if (!Page.IsPostBack )
	{
		BindData();
	}
}
void BindData()
{
	sqlStmt = 'select * from emp  ';
	ds= new DataSet ();
	da = new SqlDataAdapter (sqlStmt, cn);
	da.Fill (ds,'t1');
	DataGrid1.DataSource =ds;
	DataGrid1.DataBind ();
}

protected void ItemDB(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; 
		}
	}
}

protected void ItemCmd(object sender, System.Web.UI.WebControls.DataGridCommandEventArgs e) 
{ 
	if(e.CommandName == 'Delete')
	{ 
		this.DeleteRow(this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString()); 
	} 
	BindData();
} 

private void DeleteRow(string empid)
{ 
	SqlCommand cmd = new SqlCommand('DELETE FROM Emp WHERE employeeid ='+ empid ,cn); 
	cn.Open(); 
	cmd.ExecuteNonQuery(); 
	cn.Close(); 
} 


Permalink

<asp:DataGrid id='DataGrid1' AllowPaging =true PageSize =5 OnPageIndexChanged ='PageData' runat='server'></asp:DataGrid>

VB.NET


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
	’Put user code to initialize the page here
	If Not Page.IsPostBack Then
		Binddata()
	End If
End Sub

Protected Sub PageData(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs)
	DataGrid1.CurrentPageIndex = e.NewPageIndex
	Binddata()
End Sub

Sub Binddata()
	’Populate the DataGrid using DataSet
End Sub

C#


private void Page_Load(object sender, System.EventArgs e)
{
	// Put user code to initialize the page here
	if(! Page.IsPostBack )
	{
		Binddata();
	}
}
		 
protected void PageData(Object source , System.Web.UI.WebControls.DataGridPageChangedEventArgs   e  )
{
	DataGrid1.CurrentPageIndex = e.NewPageIndex;
	Binddata();
}

void Binddata()
{
	//Populate the DataGrid using DataSet
}
Permalink

<asp:DataGrid id='DataGrid1' AllowSorting =True OnSortCommand ='SortData'  runat='server'></asp:DataGrid>

VB.NET


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
	’Put user code to initialize the page here
	If Not Page.IsPostBack Then
	            BindDataGrid('ProductId')
	End If
End Sub

Protected Sub SortData(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs)
	BindDataGrid(e.SortExpression.ToString())
End Sub

Sub BindDataGrid(ByVal sortfield As String)
	’Fill the Dataset
	’.....
	Dim dv As DataView = ds.Tables(0).DefaultView
	dv.Sort = sortfield
	DataGrid1.DataSource = dv
	DataGrid1.DataBind()
End Sub

C#


private void Page_Load(object sender, System.EventArgs e)
{
	// Put user code to initialize the page here
	if(! Page.IsPostBack  )
	{
		BindDataGrid('ProductId');
	}
}

protected void SortData(Object source,  System.Web.UI.WebControls.DataGridSortCommandEventArgs  e )
{
	BindDataGrid(e.SortExpression.ToString());
}

void BindDataGrid(string sortfield)
{
	//Fill the Dataset
	//.....
	DataView dv    = ds.Tables[0].DefaultView;
	dv.Sort = sortfield;
	DataGrid1.DataSource = dv;
	DataGrid1.DataBind();
}
Permalink

<asp:TemplateColumn HeaderText='Email Address' HeaderStyle-Font-Bold='True'>
	<ItemTemplate>
	<a href='Mailto:<%# DataBinder.Eval(Container.DataItem,'email').ToString() %>'>
		<%# DataBinder.Eval(Container.DataItem,'email').ToString() %>
	</a>
	</ItemTemplate>
</asp:TemplateColumn>

Permalink

<asp:DataGrid id='DataGrid1' runat='server' AutoGenerateColumns='False'>
<Columns>
	<asp:TemplateColumn HeaderText='Status'>
	<ItemTemplate>
		<%#ShowStatus(bool.Parse(DataBinder.Eval(Container.DataItem,'Discontinued').ToString()))%>
	</ItemTemplate>
	</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

VB.NET


protected Function ShowStatus(ByVal someval as boolean)
  If someval = true Then
    ShowStatus = 'Yes'
  Else
    ShowStatus = 'No'
  End If
End Function

C#


protected string ShowStatus(bool  someval)
{
	if (someval == true)
	{
	return 'Yes';
	}
	else
	{
	return 'No';
	}
}
Permalink

<asp:DataGrid id='DataGrid1' runat='server' AutoGenerateColumns='False'>
<Columns>
<asp:TemplateColumn HeaderText='Sample Column'>
<ItemTemplate>
<asp:Hyperlink runat='server' Text=’<%#DataBinder.Eval(Container.DataItem, 'ProductName').ToString()%>’ NavigateUrl=’<%# 'page1.aspx?id=' + DataBinder.Eval(Container.DataItem,'ProductId').ToString() + '&Name=' + DataBinder.Eval(Container.DataItem,'ProductName').ToString()%>’ ID='Hyperlink1' NAME='Hyperlink1'/>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
Permalink

<asp:DataGrid id='DataGrid1' runat='server'></asp:DataGrid>

Use the namespace System.Data.SqlClient
VB.NET


Dim cn As SqlConnection
Dim da As SqlDataAdapter
Dim ds As DataSet
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.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()
End Sub

C#


SqlConnection cn;
SqlDataAdapter da;
DataSet ds;
private void Page_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 ();
}
Permalink

<asp:DataGrid id='DataGrid1' runat='server'></asp:DataGrid>

Use Namespace System.Data.SqlClient

VB.NET


Dim cn As SqlConnection
Dim cmd As SqlCommand
Dim rdr As SqlDataReader

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
’Put user code to initialize the page here
Try
	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()
End Try
End Sub ’Page_Load 

C#


SqlConnection cn ;
SqlCommand cmd ;
SqlDataReader rdr ; 
private void Page_Load(object sender, System.EventArgs e)
{
	// Put user code to initialize the page here
	try
	{
		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();
	}
}
Permalink

VB.NET


’Bind DataGrid
DataGrid1.Attributes.Add ('Description', 'This table displays Product Description' )

C#


//Bind DataGrid 
DataGrid1.Attributes.Add ('Description', 'This table displays Product Description' ); 

Note : By doing a ViewSource you can find the Attribute Description for the Table that displays the DataGrid data

Permalink

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 DataView
Dim 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;
Permalink

VB.NET


Protected Sub ItemDB(sender As Object, e As System.Web.UI.WebControls.DataGridItemEventArgs)
	If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.Item Then
		If e.Item.Cells(8).Text = '0' Then
			e.Item.Visible = False
		End If	
   	End If
End Sub ’ItemDB

C#


protected void ItemDB (object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
	if((e.Item.ItemType == ListItemType.Item ) || (e.Item.ItemType == ListItemType.Item ))
	{
		if( e.Item.Cells [8].Text == '0')
		{
			e.Item.Visible = false;
		}
	}
}
Permalink

Protected Sub ItemDB(sender As Object, e As System.Web.UI.WebControls.DataGridItemEventArgs)
	Dim i As Integer
	For i = 0 To e.Item.Cells.Count - 1
		e.Item.Cells(i).ToolTip = 'This is Column ' + i.ToString()
	Next 
End Sub ’ItemDB

C#


protected void ItemDB (object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
	for(int i=0 ;i<= e.Item.Cells.Count -1;i++)
	{
		e.Item.Cells[i].ToolTip = 'This is Column ' + i.ToString();
	}
}
Permalink

There are two approaches to fix this error:

  • Set the CurrentPageIndex = 0 when you bind data in the Page_EventHandler
  • Allow the error to occur and then catch it in a try block resetting the index to 0 and rebinding the grid

    VB.NET

    
    try
    	’Bind the Data
    catch ex as ArgumentOutOfRangeException
    	DataGrid1.CurrentPageIndex  = 0;
    	’Bind the Data
    end try
    

    C#

    
    try
    {
    	//Bind the Data
    }
    catch(ArgumentOutOfRangeException ex )
    { 
    	DataGrid1.CurrentPageIndex  = 0;
    	//Bind the Data
    }
    
    
Permalink

Share with

Share on twitter
Share on facebook
Share on linkedin

Couldn't find the FAQs you're looking for?

Please submit your question and answer.