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:
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.
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.
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
IfNot Page.IsPostBack Then
’Populate the dataSet
’Bind the dataGrid with the dataView
DataGrid1.DataSource = BindTheDataClass.Binddata().Tables(0).DefaultView
DataGrid1.DataBind()
EndIfEnd Sub ’Page_Load
Protected Sub 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
’Bydefault the Datagrid Header is shown incase there isnoData Available
’So incaseofNoDatafound
’Check the ListItemType.Header
If e.Item.ItemType = ListItemType.Header Then
Dim 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 Datagrid
Dim j AsIntegerFor j = i - 1To1 Step -1
e.Item.Cells.RemoveAt(j)
NextEndIfEndIfEnd Sub ’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);
}
}
}
}
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.
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
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')
IfNot Page.IsPostBack Then
da = New SqlDataAdapter('SELECT orderid FROM orders', cn)
ds = New DataSet
da.Fill(ds, 'Orders')
DataGrid1.DataSource = ds
DataGrid1.DataBind()
EndIfEnd Sub ’Page_Load
Protected Sub ItemDB(ByVal sender AsObject, ByVal e As DataGridItemEventArgs)
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
Dim 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)
EndIfEnd Sub ’ItemDB
Function GetOrderDetails(ByVal idAsInteger) 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 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;')
IfNot Page.IsPostBack Then
BindData()
EndIfEnd Sub
Sub BindData()
DataGrid1.DataSource = GetData('Select * from Region')
DataGrid1.DataBind()
End Sub
Function GetData(ByVal strSql AsString) As DataSet
da = New SqlDataAdapter(strSql, cn)
ds = New DataSet()
da.Fill(ds)
Return ds
EndFunction
Protected Sub ItemCommand(ByVal sourceAsObject, _
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)
EndIfEnd Sub
Sub FillTheData(ByVal RegionID AsString, ByVal RegionDescription AsString)
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 AsException
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 ;
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();
}
}
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.
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.
protected Sub dgPreRender(ByVal sender As Object, 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)
End Sub
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);
}
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 AsNew StringWriter
Dim htmlWrite AsNew HtmlTextWriter(stringWrite)
Dim dGrid AsNew DataGrid
dGrid = dGridExport
dGrid.HeaderStyle.Font.Bold = True
dGrid.DataBind()
dGrid.RenderControl(htmlWrite)
httpResp.Write(stringWrite.ToString)
httpResp.End()
End Sub
C#
privatevoidPage_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here//Bind the DataGrid to DataSet
DataGridToExcel (DataGrid1, Response);
}
protectedvoidDataGridToExcel(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();
}
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
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()).
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
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 As Integer
protected function getCount() As Integer
count = count + 1
Return count
EndFunctionPrivate Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
’Populate the Datagrid populating datafrom the database
’.....
End Sub
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.
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
IfNot Page.IsPostBack Then
BindGrid('')
EndIfEnd Sub
Sub 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()
EndIfEnd Sub
Protected Sub 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)
NextEndIfEnd Sub
Protected Sub ItemCommand(ByVal sourceAsObject, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs)
If (e.CommandName = 'alpha') Then
BindGrid(e.CommandArgument.ToString())
EndIfEnd Sub
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 ());
}
}
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
Public Class newLabelColumn
Implements ITemplate
Public Sub New()
End Sub ’New
’Addconstructorstuff here
Public Sub InstantiateIn(ByVal containerAs Control) Implements System.Web.UI.ITemplate.InstantiateIn
Dim label1 AsNew Label
AddHandler label1.DataBinding, AddressOf Me.BindLabelColumn
container.Controls.Add(label1)
End Sub ’InstantiateIn
Public Sub BindLabelColumn(ByVal sender AsObject, ByVal e As EventArgs)
Dim lbl As Label = CType(sender, Label)
Dim containerAs 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
EndClass ’newLabelColumn
’Fill the Dataset
Dim objtc AsNew TemplateColumn
objtc.HeaderText = 'Full Name'
objtc.ItemTemplate = New newLabelColumn
DataGrid1.Columns.Add(objtc)
DataGrid1.DataSource = ds
DataGrid1.DataBind()
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#
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 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 ';
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();
}
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
IfNot Page.IsPostBack Then
’Bind the dataGrid to DataView
EndIfEnd Sub
Protected Sub 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’)')
EndIfNextEnd Sub
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 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 Datato datagrid
End Sub
Protected Sub UPTotal(ByVal _unitprice AsDouble)
UnitPrice += _unitprice
End Sub ’UPTotal
Public Sub 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()
EndIfEndIfEnd Sub ’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 ();
}
}
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
Protected Sub SelectedIndexChg(ByVal sender As Object, ByVal e As System.EventArgs)
Label1.Text = CType(DataGrid1.SelectedItem.FindControl('lbl1'), Label).Text
End Sub
’Fill the DataSet ds withdatafromdatabase
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();
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
IfNot IsPostBack Then
’Populate the datagrid
EndIfEnd Sub
protected Sub chkChanged(ByVal sender AsObject, ByVal e As System.EventArgs)
Response.Write('CheckChanged Event')
End Sub
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');
}
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
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#
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 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()
EndIfEnd 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 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'End Try
myCommand.Connection.Close()
BindGrid()
End Sub ’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 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=;'IfNot Page.IsPostBack Then
BindGrid()
EndIfEnd 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 AsString = CType(e.Item.Cells(3).Controls(0), TextBox).Text
Dim quantity AsString = CType(e.Item.Cells(4).Controls(0), TextBox).Text
Dim discount AsString = CType(e.Item.Cells(5).Controls(0), TextBox).Text
Dim orderid AsInteger = CInt(DataGrid1.DataKeys(CInt(e.Item.ItemIndex)))
Dim productid AsString = CType(e.Item.Cells(2).Controls(0), TextBox).Text
Try
Dim updateCmd AsString = 'UPDATE [Order Details] SET UnitPrice = @UnitPrice,' + 'Quantity = @Quantity, Discount = @Discount where OrderId =@OrderId and ProductId=@ProductId'
Dim cn AsNew SqlConnection(strConn)
Dim myCommand AsNew 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 AsException
lblError.Visible = True
lblError.Text = ex.Message
End Try
End Sub ’DataGrid1_Update
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
PublicFunction GoDoReShape(ByVal ds As DataSet) As DataSet
Dim NewDs AsNew DataSet()
NewDs.Tables.Add()
’Create Two Columnswithnames'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
’DeclareArray
Dim 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;
}
ProtectedFunction CheckStatus(ByVal prdStatus As Boolean) As BooleanIfprdStatus = False ThenReturnTrueElseReturnFalseEndIfEndFunction
C#
protectedboolCheckStatus(bool prdStatus){
//If the Discontinued field is '0'if (prdStatus==false)
{
returntrue;
}
//If the Discontinued field is '1'else
{
returnfalse;
}
}
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
IfNot Page.IsPostBack Then
BindGrid()
EndIfEnd Sub ’Page_Load
Sub BindGrid()
’Bind the Datagrid with dataSet
End Sub ’BindGrid
Protected Sub EditCmd(ByVal sender AsObject, ByVal e As DataGridCommandEventArgs)
DataGrid1.EditItemIndex = CInt(e.Item.ItemIndex)
BindGrid()
End Sub ’EditCmd
Public Sub CancelCmd(ByVal sender AsObject, ByVal e As DataGridCommandEventArgs)
DataGrid1.EditItemIndex = -1
BindGrid()
End Sub ’CancelCmd
Protected Sub 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).Text
Dim 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 = -1
Catch ex AsException
Response.Write(ex.Message.ToString())
End Try
BindGrid()
EndIfEnd Sub ’UpdateCmd
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
IfNot Page.IsPostBack Then
BindDataGrid('ProductId')
EndIfEnd Sub
Protected Sub SortData(ByVal sourceAsObject, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs)
BindDataGrid(e.SortExpression.ToString())
End Sub
Sub BindDataGrid(ByVal sortfield AsString)
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 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.AntiqueWhite
EndIfEndIfEnd Sub
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 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'IfNot Page.IsPostBack Then
BindGrid()
EndIfEnd 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/NoforTrue/False
Protected Function ShowVal(ByVal blnval AsBoolean) AsStringIf blnval = TrueThenReturn'Yes'ElseReturn'No'EndIfEndFunction ’ShowVal
’Bind the Datato 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
EndFunction ’BindTheDiscontinued
’Set the Textof the Dropdownlist to the fieldvalueinDatabase
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 UpdateCancelPublic 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 inClass GetData.cs
Dim mycn As SqlConnection
Dim myda As SqlDataAdapter
Dim mycmd As SqlCommand
Dim ds As DataSet
Dim strConn AsString
Dim 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 AsException
Throw NewException(ex.Message.ToString())
Finally
mycn.Close()
End Try
EndFunction ’GetDataFromTable
PublicFunction 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 AsException
Throw NewException(ex.Message.ToString())
Finally
End Try ’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 As Object, e As System.EventArgs)’Put user code to initialize the page hereIfNot Page.IsPostBack Then’Populatethe DataGridEndIfEndSub ’Page_Load ProtectedSub ItemDB(ByVal s As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)Ife.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem ThenIfe.Item.Cells(1).Text = ' ' Thene.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';
}
}
}
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
IfNot Page.IsPostBack Then
’Populate the DataGrid
EndIfEnd Sub
Protected Sub ItemCmd(ByVal sourceAsObject, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs)
If e.CommandName = 'Show'Then
Response.Write(e.Item.Cells(1).Text)
EndIfEnd Sub
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);
}
}
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
SelectCaseTrim(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'CaseElse
e.Item.Cells(3).Text = e.Item.Cells(3).Text
EndSelectendifend sub
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 AsNew 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;
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();
}
<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 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()
EndIfEnd 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 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();')
ExitEndSelectEnd Sub ’ItemDB
Protected Sub ItemCmd(sender AsObject, e As System.Web.UI.WebControls.DataGridCommandEventArgs)
If e.CommandName = 'Delete'Then
Me.DeleteRow(Me.DataGrid1.DataKeys(e.Item.ItemIndex).ToString())
EndIf
BindData()
End Sub ’ItemCmd
Private Sub DeleteRow(empid AsString)
Dim cmd AsNew 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;
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();
}
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
IfNot Page.IsPostBack Then
Binddata()
EndIfEnd Sub
Protected Sub PageData(ByVal sourceAsObject, 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#
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
}
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
IfNot Page.IsPostBack Then
BindDataGrid('ProductId')
EndIfEnd Sub
Protected Sub SortData(ByVal sourceAsObject, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs)
BindDataGrid(e.SortExpression.ToString())
End Sub
Sub BindDataGrid(ByVal sortfield AsString)
’Fill the Dataset
’.....
Dim dv As DataView = ds.Tables(0).DefaultView
dv.Sort = sortfield
DataGrid1.DataSource = dv
DataGrid1.DataBind()
End Sub
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
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;
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
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 AsException
Response.Write(ex.Message.ToString())
Finally
rdr.Close()
cn.Close()
End Try
End Sub ’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();
}
}
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;
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