Friday, March 27, 2009

How To Perform Paging with the DataGrid Windows Control by Using Visual C# .NET

Steps to Add Paging to a DataGrid Windows Control

When you page a DataGrid, you display data in page-size "chunks," that is, one page of records at a time. The sample code to follow copies the DataRow objects for each page from the DataSet in memory to a temporary table. The temporary table is then bound to the DataGrid control.

1. Open a new Visual C# .NET Windows Application project.
2. Add DataGrid control, and set its ReadOnly property to True.
3. Place the following additional controls on Form1, and set their properties as shown below:
Collapse this tableExpand this table


Control Name Property Text Property
Button btnFirstPage First Page
Button btnNextPage Next Page
TextBox txtDisplayPageNo
Button btnPreviousPage Previous Page
Button btnLastPage Last Page
TextBox txtPageSize 5
Button btnFillGrid Fill Grid
DataGrid dataGrid1

4. Copy and paste the following code into the top of Form1's Code window. Make sure that each namespace is referenced just once. System and System.Data may already be referenced by default.

using System;
using System.Data;
using System.Data.SqlClient;


5. Copy and paste the following code at the top of public class Form1 to declare form-level variables for Form1:

SqlDataAdapter da;
DataSet ds;
DataTable dtSource;
int PageCount;
int maxRec;
int pageSize;
int currentPage;
int recNo;


6. Copy and paste the following code immediately after the static void Main method so that this code is form-level in scope:

private void LoadPage()

{
int i;
int startRec;
int endRec;
DataTable dtTemp;

//Clone the source table to create a temporary table.
dtTemp = dtSource.Clone();

if (currentPage == PageCount)
{
endRec = maxRec;
}
else
{
endRec = pageSize * currentPage;
}
startRec = recNo;

//Copy rows from the source table to fill the temporary table.
for (i = startRec; i < endRec; i++) {
dtTemp.ImportRow(dtSource.Rows[i]);
recNo += 1;
}
dataGrid1.DataSource = dtTemp;
DisplayPageInfo();
}

private void DisplayPageInfo()
{
txtDisplayPageNo.Text = "Page " + currentPage.ToString() + "/ " + PageCount.ToString();
}

private bool CheckFillButton()
{
// Check if the user clicks the "Fill Grid" button.
if (pageSize == 0)
{
MessageBox.Show("Set the Page Size, and then click the Fill Grid button!");
return false;
}
else
{
return true;
}
}


7. Paste the following code into the Form1_Load event procedure:

//Open Connection.
SqlConnection conn = new SqlConnection("Server=server;uid=login;pwd=pwd;database=northwind");

//Set the DataAdapter's query.
da = new SqlDataAdapter("select * from customers", conn);
ds = new DataSet();

//Fill the DataSet.
da.Fill(ds, "customers");

//Set the source table.
dtSource = ds.Tables["customers"];


8. Modify the connection string, which appears in the preceding code, as appropriate for your environment:

SqlConnection conn = new SqlConnection("Server=server;uid=login;pwd=pwd;database=northwind");


9. Double-click Fill Grid to open the code window for btnFillGrid. Copy and paste the following code into the btnFillGrid_Click event procedure:

// Set the start and max records.
pageSize = Convert.ToInt32(txtPageSize.Text);
maxRec = dtSource.Rows.Count;
PageCount = maxRec / pageSize;

//Adjust the page number if the last page contains a partial page.
if ((maxRec % pageSize) > 0) {
PageCount += 1;
}

// Initial seeings
currentPage = 1;
recNo = 0;

// Display the content of the current page.
LoadPage();


10. Double-click First Page to open the code window for btnFirstPage. Copy and paste the following code into the btnFirstPage_Click event procedure:

if (CheckFillButton() == false) {
return;
}

//Check if you are already at the first page.
if (currentPage == 1) {
MessageBox.Show("You are at the First Page!");
return;
}

currentPage = 1;
recNo = 0;
LoadPage();


11. Double-click Next Page to open the code window for btnNextPage. Copy and paste the following code into the btnNextPage_Click event procedure:

//If the user did not click the "Fill Grid" button, then return.
if (CheckFillButton() == false) {
return;
}

//Check if the user clicks the "Fill Grid" button.
if (pageSize == 0) {
MessageBox.Show("Set the Page Size, and then click the Fill Grid button!");
return;
}

currentPage += 1;
if (currentPage > PageCount) {
currentPage = PageCount;
//Check if you are already at the last page.
if (recNo == maxRec) {
MessageBox.Show("You are at the Last Page!");
return;
}
}
LoadPage();


12. Double-click Previous Page to open the code window for btnPreviousPage. Copy and paste the following code into the btnPreviousPage_Click event procedure:

if (CheckFillButton() == false) {
return;
}

if (currentPage == PageCount) {
recNo = pageSize * (currentPage - 2);
}

currentPage -= 1;
//Check if you are already at the first page.
if (currentPage < 1) {
MessageBox.Show("You are at the First Page!");
currentPage = 1;
return;
}
else {
recNo = pageSize * (currentPage - 1);
}
LoadPage();


13. Double-click Last Page to open the code window for btnLastPage. Copy and paste the following code into the btnLastPage_Click event procedure:

if (CheckFillButton() == false) {
return;
}

//Check if you are already at the last page.
if (recNo == maxRec) {
MessageBox.Show("You are at the Last Page!");
return;
}
currentPage = PageCount;
recNo = pageSize * (currentPage - 1);
LoadPage();


14. Press the F5 key to build and run the project.
15. By default, the Page Size is set to 5 records. You can change this in the text box.
16. Click Fill Grid. Notice that the DataGrid is filled with 5 records.
17. Click First Page, Next Page, Previous Page, and Last Page to browse between pages.

Labels:

How Sorting ASP.NET DataGrid

Where are all of the steps for sorting an ASP.NET DataGrid detailed? Everytime I start to sort a grid, I have to look in several places to get all of the steps?

Although all of the steps to set up an ASP.NET DataGrid seem to be documented in one place or another, there seems to be one step missing from each description that I have found. Therefore, in attempting to simplify the process, and list every tiny detail, I probablly will miss one too, but here goes. If I should miss a step myself, remember I wrote this article because it's not a well documented, straight-forward process.

Assuming that you have placed a DataGrid on your ASP.NET page, I follow these steps.

1) Right-click the DataGrid and select the Property Builder menu option. On the General Tab, check the Allow Sorting Checkbox.

2) On the Columns Tab, for each column that you want to sort, enter the query field name of that column in the Sort Expression box. This is what turns on the underline on the respective grid column. If a column header is not underlined in the designer, it will not be sortable. The underline will only appear when you click the Apply button or the Ok button to exit the Property Builder. By the way, this is the step that some books by well-know authors leave out and it can be baffling why the header text is not underlined.

3) Create a DataView object at the class level, such as the following. Remember, in a Stateless environment, no variables are automatically saved, and therefore must be saved in Session Variables. So, I save the contents of the DataView in a Session Variable thoughout it's usage.


private DataView dv;


4) In the Page Load event, I will place some code that looks something like this.


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


5) The ShowData method is responsible for getting the data and calling the BindData method.


private void ShowData()
{
int authorID = Convert.ToInt32(Session["AuthorID"]);
DateTime stDate = (DateTime)Session["StartDate"];
DateTime endDate = (DateTime)Session["EndDate"];
DataTable dt = blj.GetDictationByAuthorID(authorID, stDate, endDate);
// set the dataview object to the datatable DefaultView
dv = dt.DefaultView;
Session["DictatedDV"] = dv;
BindData("");
}


6) Iwill call the BindData method to bind the dataview to the grid.


private void BindData(string sortExpression)
{
// reset the dataview, else it will be undefined value!
dv=(DataView)Session["DictatedDV"];
if(sortExpression.Length>0)
{
dv.Sort=sortExpression;
// save the dataview in stateless environment
Session["DictatedDV"] = dv;
}
this.DataGrid1.DataSource=dv;
this.DataGrid1.DataBind();
}


7) Switch back to the designer and click on the DataGrid and then show the Property window for the grid. Click the events button(lighnning bolt) and double-click in the SortCommand event. That will create a DataGrid1_SortCommand event. Enter the code shown below into the event. In this event, I set the SortExpression, which you will recall is the field name of the data column in the designer. This is actually a string name of the column to sort on.


private void DataGrid1_SortCommand(object source,
System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
BindData(e.SortExpression);
}


8) Now, we can sort, but only in one direction, ascending. At this point our grid does not support sorting in both directions. That can be solved by enhancing the code for the SortCommand event shown above. I will simplly remember the last order that we sorted in and reverse that direction with the code shown below.


private void DataGrid1_SortCommand(object source,
System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
string sortExpression = (string)Session["SortExp"];
string sortDirection = (string)Session["SortDir"];

if(sortExpression != e.SortExpression)
{
sortExpression = e.SortExpression;
sortDirection = "asc";
}
else
{
if(sortDirection == "asc")
sortDirection = "desc";
else
sortDirection = "asc";
}

Session["SortExp"] = sortExpression;
Session["SortDir"] = sortDirection;
BindDataGrid(sortExpression + " " + sortDirection);
}

Labels:

How Multiple Column Dropdownlist for the ASP.NET DataGrid

Introduction

Based on my previous control "Multiple Column DropDownList for ASP.NET", I received many emails asking for the same control to be used in the DataGrid for web applications. Here we go.. This control can be used as the regular MS DropDownList in the DataGrid and also as a regular dropdownlist. It has all the properties, like DataTextField, DataValueField, DataSource, SelectedIndex etc. The download file contains the samples both in VB.NET and C#. In this sample, I have used the Northwind database of SQL Server.
Building the Control

The following web server controls were used to build this control:

1. TextBox
2. Label
3. Panel

Adding the Control to DataGrid

This control can be added either to the ItemTemplate or EditItemTemplate of the DataGrid through Property Builder.

1. Drop a DataGrid onto your webform.
2. Right click the DataGrid and select Property Builder and select Columns.
3. A bound column may or may not be required, I have shown samples of both.
4. Add two bound columns, set the header and the text field: SupplierID and CompanyName.
5. Add one Template Column and set the header text to Products.
6. Uncheck the checkbox "Create columns automatically at run time".
7. Click OK.
8. Now right click the DataGrid and select Edit Template, now either you could add this in ItemTemplate or EditItemTemplate.
9. Set the properties of the control, like CssClass, GridRowcolor, DataTextfield etc.
10. Close the template box.

Points to Note:

The DataValueField property is readonly, which means you cannot set the value, so make sure that in your query, the row value field is always the first column, which will not be displayed in the dropdown. The DataTextField returns an integer value, so while setting this property, type the column position from your "SELECT" statement, which needs to get displayed in the textbox. (For e.g., to display the second column "LastName" in the textbox, set DataValueField =2.) If your DataGrid is inside the "Table/Div/Span", then make sure the "Position" attribute in the "Style" property is set to absolute, and if not used in any of these tags, then set the DataGrid's Style property.

Make sure that the HorizontalAlign and VerticalAlign properties of the ItemStyle of your DataGrid is set as shown, else the control may not be positioned properly inside the DataGrid. E.g.:

<ItemStyle HorizontalAlign="Left" VerticalAlign="Top"></ItemStyle>

See the code below. E.g., to populate the dropdown with FirstName and LastName:


SELECT Employeeid,Firstname,LastName
From Employees

Now if added in the EditItemTemplate (based on your requirement, bounded column may or may not be required), in my sample I used two <BoundColumn>s:


<ASP:DATAGRID id="jskDataGrid" runat="server"
Font-Size="8pt" HeaderStyle-ForeColor="Tan"
AutoGenerateColumns="False" HeaderStyle-BackColor="Maroon"
HeaderStyle-Font-Bold="True" Font-Name="Verdana" ShowFooter="false"
BorderColor="Tan" DataKeyField="SupplierID"
OnUpdateCommand="MyDataGrid_Update" OnCancelCommand="MyDataGrid_Cancel"
OnEditCommand="MyDataGrid_Edit" CellSpacing="0" CellPadding="3"
Width="800" Style="Position:absolute;Top:0px;Left:0px">

<HeaderStyle Font-Bold="True" ForeColor="Tan" BackColor="Maroon"></HeaderStyle>
<Columns>
<asp:EditCommandColumn ButtonType="LinkButton"
UpdateText="Update" CancelText="Cancel" EditText="Edit">
<ItemStyle VerticalAlign="Top"></ItemStyle>
</asp:EditCommandColumn>
<asp:BoundColumn DataField="SupplierID"
ReadOnly="True" HeaderText="Supplier ID">
<ItemStyle Wrap="False" VerticalAlign="Top"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="CompanyName"
ReadOnly="True" HeaderText="Company Name">
<ItemStyle Wrap="False" VerticalAlign="Top"></ItemStyle>
</asp:BoundColumn>
<asp:TemplateColumn HeaderText="Products">
<ItemStyle HorizontalAlign="Left" VerticalAlign="Top"></ItemStyle>
<!-- Set these two properties as shown-->
<%# DataBinder.Eval(Container.DataItem, "ProductName") %>
</ItemTemplate>
<EditItemTemplate>
<TABLE cellSpacing="0" cellPadding="0" width="100%" border="0">
<TR>
<TD>
<jsk:mcDDList id="McDDList1"
Width="200"
SelectedIndex='<%# DataBinder.Eval(Container.DataItem,
"ProductID") %>'
cssClass="cStyle" Runat="server"
DataSource="<%# PopulateDDList()%>"
DataTextField="2">
</jsk:mcDDList>
</TD>
</TR>
</TABLE>
</EditItemTemplate>
</asp:TemplateColumn>
</Columns>
</ASP:DATAGRID>

If you want to show the existing values then add the "SelectedIndex" property.
Properties

* DataTextField - The field to be shown in the Ccontrol.
* DataValueField - Read only property (value field to identify the row - default is first column {0}).
* DataSource - DataSet to populate the dropdown.
* DDTextboxReadonly - If false, can type your own text.
* GridRowColor - OnMouseMove changes the row color.
* GridTextColor - OnMouseMove changes the text color.
* ListBoxHeight - Sets the height of the dropdown.
* ReturnsValue - To get the text, set it to false. To get the value, set it to true, while updating.
* SelectedIndex - If set, shows the existing value in the dropdown.

Populating the DataGrid


private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here

if (! IsPostBack)
{
BindDataGrid();
}
}

protected void BindDataGrid()
{
string sqlStr = "SELECT S.CompanyName, S.SupplierID," +
" P.ProductName, P.ProductID " +
"from Suppliers S inner join Products P " +
"on S.SupplierID = P.SupplierID ";
sqlDa = new SqlDataAdapter(sqlStr, SqlCon);
ds = new DataSet();
sqlDa.Fill(ds, "Prod");
jskDataGrid.DataSource = ds.Tables["Prod"];
jskDataGrid.DataBind();
}

Populating the DropDownList


public DataSet PopulateDDList()
{
string sqlString = " select ProductID, ProductName, " +
"CategoryName as Name,UnitPrice as Price " +
"from Products p inner join Categories c " +
"on p.categoryid = c.categoryid ";
SqlDataAdapter ad = new SqlDataAdapter(sqlString,SqlCon);
DataSet ds = new DataSet();
ad.Fill(ds,"Categories");
return ds;
}

Codes to Edit/Update/Cancel


protected void jskDataGrid_Edit(object sender, DataGridCommandEventArgs e)
{
jskDataGrid.EditItemIndex = e.Item.ItemIndex;
BindDataGrid();
}

protected void jskDataGrid_Cancel(object sender, DataGridCommandEventArgs e)
{
jskDataGrid.EditItemIndex = -1;
BindDataGrid();
}

protected void jskDataGrid_Update(object sender, DataGridCommandEventArgs e)
{
try
{
string itemValue;
string itemText;

// To get the DataValueField of the DropDown

((ddList.mcDDList)e.Item.FindControl("McDDList1")).ReturnsValue = true;
itemValue =
((ddList.mcDDList)e.Item.FindControl("McDDList1")).Text.ToString();

// To get the DataTextField of the Dropdown

((ddList.mcDDList)e.Item.FindControl("McDDList1")).ReturnsValue = false;
itemText =
((ddList.mcDDList)e.Item.FindControl("McDDList1")).Text.ToString();

//write your update query

//update table set col1 = itemtext where col2 = itemvalue

//Execute the Query


jskDataGrid.EditItemIndex = -1;
BindDataGrid();
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
/*Close your Connection */
}
}

Points of Interest

The control is built mostly using JavaScript. There is a property "DDTextboxReadonly", this property is used to enable/disable the textbox, means either you could select the text from the list or you could type.
Using the Intellisense

As in my previous article, I showed how to use the Intellisense. The zip file contains the .xsd, copy it to the following location:

* C:\Program Files\Microsoft Visual Studio .NET 2003\Common7\Packages\schemas\xml

and in the <body> tag of your aspx page, add the following code:


<body MS_POSITIONING="GridLayout"
xmlns:jsk="urn:http://schemas.ksjControls.com/DGDD/ASPNET">

Labels:

How DataGrid Editing in C#

using System;
using System.Collections;
using System.IO;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Data.SqlClient;


public class InOut : Page
{

public DataGrid gridBO;
public string sqlStatement1 = "Select * FROM Employee WHERE employeeDepartmentId = 1 ORDER BY employeeDepRank";




protected void page_load(Object s, EventArgs e)
{

if(!IsPostBack)
{

BindData();

}


}

protected void BindData()
{
OleDbConnection objConn = new OleDbConnection(ConfigurationSettings.AppSettings["wabash"]);
OleDbCommand objCmd = new OleDbCommand(sqlStatement1, objConn);
objConn.Open();
OleDbDataReader objRdr = objCmd.ExecuteReader();
gridBO.DataSource = objRdr;
gridBO.DataBind();
objRdr.Close();
objConn.Close();
}


protected void gridBO_Edit(Object s, DataGridCommandEventArgs e)
{
gridBO.EditItemIndex = e.Item.ItemIndex;
BindData();

}

protected void gridBO_Cancel(Object s, DataGridCommandEventArgs e)
{
gridBO.EditItemIndex = -1;
BindData();

}

protected void gridBO_Update(Object s, DataGridCommandEventArgs e)
{
int employeeDepRank = (int)gridBO.DataKeys[e.Item.ItemIndex];
string strStatus = ((TextBox)e.Item.Cells[0].Controls[0]).Text;
string strComments = ((TextBox)e.Item.Cells[3].Controls[0]).Text;
string strCmd = "UPDATE Employee Set employeeStatus='" + strStatus + "', employeeComments='" + strComments + "' WHERE employeeDepRank=" + employeeDepRank;

OleDbConnection objConn = new OleDbConnection(ConfigurationSettings.AppSettings["wabash"]);
OleDbCommand objCmd = new OleDbCommand(strCmd, objConn);

objConn.Open();
objCmd.ExecuteNonQuery();
objConn.Close();

gridBO.EditItemIndex = -1;
BindData();

}


*************************************************************************************

<%@ Page Language="C#" Debug="true" Inherits="InOut" Src="myles.cs" %>
<script runat="server">


</script>
<html>
<head>
</head>
<body>
<form runat="server">
<!-- NEW IN OUT DATAGRID -->
<center>
<asp:DataGrid id="gridBO" runat="server" OnEditCommand="gridBO_Edit" OnCancelCommand="gridBO_Cancel" OnUpdateCommand="gridBO_Update" DataKeyField="employeeDepRank" AutoGenerateColumns="False">
<ItemStyle font-name="Arial" font-size="10pt" forecolor="#000000" />
<HeaderStyle font-name="Arial" font-size="12pt" font-bold="true" backcolor="#658bbc" forecolor="#FFFFFF" />
<AlternatingItemStyle font-name="Arial" font-size="10pt" backcolor="#e3efff" />
<Columns>
<asp:BoundColumn DataField="employeeStatus" HeaderText="Name" />
<asp:BoundColumn DataField="employeeName" HeaderText="Name" ReadOnly="true" />
<asp:BoundColumn DataField="employeePhone" HeaderText="Phone" ReadOnly="true" />
<asp:BoundColumn DataField="employeeComments" HeaderText="Comments" />
<asp:EditCommandColumn EditText="Edit" CancelText="Cancel" UpdateText="Update" />
</Columns>
</asp:DataGrid>
</center>
<center><asp:Label id="lblStatus" runat="server"> </asp:Label>
</center>
<!-- END IN OUT DATAGRID -->
</form>
</body>
</html>

Labels:

How Object Binding in DataGrid with C#

Introduction

In this article, I will discuss how to bind objects such as an ArrayList to a DataGrid control using C# and ADO.NET.

Binding an ArrayList

If you create an ArrayList and bind it to the DataGrid control, DataGrid does not display the contents. For example, the following code creates an ArrayList objects, add items to it, and binds it to the DataGrid:

ArrayList list = new ArrayList();
list.Add(1);
list.Add(2);
list.Add(3);
dataGrid1.DataSource = list;

The problem with this code is DataGrid is not aware of the contents of the ArrayList. DataGrid can only display contents having a format of schema where there should be a column name and column type.

The Solution

The solution of the problem is to create a class that exposes an integer as its property. Then you create an ArrayList and bind it to the DataGrid. For example, the following code creates an ArrayList of MyClass object, which takes one value as constructor parameter. Here MyClasss exposes this value as an int property.

ArrayList list = new ArrayList();
list.Add(new MyClass(1);
list.Add(new MyClass(2);
list.Add(new MyClass(3);
dataGrid1.DataSource = list;

The Complete Code

Here is a class with integer and string properties.

public class BindingObject
{
private int intMember;
private string stringMember;
private string nullMember;
public BindingObject(int i, string str1, string str2)
{
intMember = i;
stringMember = str1;
nullMember = str2;
}
public int IntMember
{
get { return intMember; }
}
public string StringMember
{
get { return stringMember; }
}
public string NullMember
{
get { return nullMember; }
}
}

Now you can create an ArrayList of this class objects and bind it to the DataGrid as following:

ArrayList list = new ArrayList();
list.Add(new BindingObject(1, "One", null));
list.Add(new BindingObject(2, "Two", null));
list.Add(new BindingObject(3, "Three", null));
dataGrid1.DataSource = list;

Labels:

How C# DataGrid with DataSet

Create Database and Table accordingly.

/*
* Simple C# example to illustrate the usage of Dataset with DataGrid
* Need to change the url and query accordingly
*/

using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Windows.Forms;

public class DataGridSample:Form{
DataGrid myGrid;

SqlConnection con;
SqlDataAdapter adapter;
DataSet ds;
Button ok, cancel;

SqlParameter workParam = null;

// apply to the columns in the table
string query = "select CardNo,CardType,CardAmount, CardHolderName from CardTest";

// change the Server ,uid, pwd and database accordingly
string url = "server=TR4;uid=sa;pwd= ;database=RBSGTest";



static void Main(){
Application.Run(new DataGridSample());
}

public DataGridSample(){
InitializeComponent();
}

public void InitializeComponent(){
this.ClientSize = new System.Drawing.Size(550, 450);
myGrid = new DataGrid();
myGrid.Location = new Point (10,10);
myGrid.Size = new Size(500, 350);
this.Text = "C# DataGrid with DataSet - Example";
this.Controls.Add(myGrid);

ok = new Button();
ok.Location = new Point(10, 375);
ok.Size = new Size(70, 30);
ok.TabIndex = 1;
ok.Text = "OK";
this.Controls.Add(ok);
ok.Click += new System.EventHandler(button_Click);

cancel = new Button();
cancel.Location = new Point(95, 375);
cancel.Size = new Size(70, 30);
cancel.TabIndex = 1;
cancel.Text = "Cancel";
this.Controls.Add(cancel);
cancel.Click += new System.EventHandler(button_Click);

ConnectToData(); // establish database connection and create DataSet
myGrid.SetDataBinding(ds, "CardTest");
DataTable t = ds.Tables["CardTest"];
t.RowChanged += new DataRowChangeEventHandler(Row_Changed);

}

public void ConnectToData(){
ds = new DataSet();
con = new SqlConnection(url);
adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(query, con);
adapter.Fill(ds, "CardTest");
insertCommand();
updateCommand();
}

public void updateCommand()
{
string query = "Update CardTest Set CardHolderName = @CardHolderName, CardType = @CardType, CardAmount = @CardAmount WHERE CardNo = @CardNo";

adapter.UpdateCommand = new SqlCommand(query, con);

workParam = adapter.UpdateCommand.Parameters.Add("@CardNo", SqlDbType.NChar);
workParam.SourceColumn = "CardNo";
workParam.SourceVersion = DataRowVersion.Original;

workParam = adapter.UpdateCommand.Parameters.Add("@CardType", SqlDbType.NChar, 50);
workParam.SourceVersion = DataRowVersion.Current;
workParam.SourceColumn = "CardType";

workParam = adapter.UpdateCommand.Parameters.Add("@CardAmount", SqlDbType.Int);
workParam.SourceColumn = "CardAmount";
workParam.SourceVersion = DataRowVersion.Current;

workParam = adapter.UpdateCommand.Parameters.Add("@CardHolderName", SqlDbType.NChar, 50);
workParam.SourceColumn = "CardHolderName";
workParam.SourceVersion = DataRowVersion.Current;
}


public void button_Click(object sender, EventArgs evArgs)
{
if (sender==ok){
UpdateValue(); // update the database once everything done.
}
if (sender==cancel) {
this.Dispose();
}
}


private void Row_Changed(object ob, DataRowChangeEventArgs e)
{
DataTable t = (DataTable) ob;
Console.WriteLine("RowChanged " + e.Action.ToString() + "\t" + e.Row.ItemArray[0]);
}

public void insertCommand()
{
string insertQuery = "Insert into CardTest VALUES (@CardNo, @CardType, @CardAmount, @CardHolderName)";
adapter.InsertCommand = new SqlCommand(insertQuery, con);

workParam = adapter.InsertCommand.Parameters.Add("@CardNo", SqlDbType.NChar);
workParam.SourceColumn = "CardNo";
workParam.SourceVersion = DataRowVersion.Current;

workParam = adapter.InsertCommand.Parameters.Add("@CardType", SqlDbType.NChar, 50);
workParam.SourceVersion = DataRowVersion.Current;
workParam.SourceColumn = "CardType";

workParam = adapter.InsertCommand.Parameters.Add("@CardAmount", SqlDbType.Int);
workParam.SourceColumn = "CardAmount";
workParam.SourceVersion = DataRowVersion.Current;

workParam = adapter.InsertCommand.Parameters.Add("@CardHolderName", SqlDbType.NChar, 50);
workParam.SourceVersion = DataRowVersion.Current;
workParam.SourceColumn = "CardHolderName";
}


public void UpdateValue()
{
try
{
adapter.Update(ds, "CardTest");
Console.Write("Updating DataSet succeeded!");
}
catch(Exception e)
{
Console.Write(e.ToString());
}
}

}

Labels:

HOW TO: Loop Through and Examine CheckBox Control Values in a DataGrid Column by Using ASP.NET and Visual Basic .NET

Create an ASP.NET Web Application by Using Visual Basic .NET
Start Microsoft Visual Studio .NET.
On the File menu, point to New, and then click Project.
In the New Project dialog box, click Visual Basic Projects under Project Types, and then click ASP.NET Web Application under Templates.
In the Location box, replace the WebApplication# default name with MyWebApp. If you are using the local server, you can leave the server name as http://localhost. The resulting Location box appears as follows:
http://localhost/MyWebApp
Create the Sample Web Form Page
1)Add a new Web Form to the ASP.NET Web application as follows:
Right-click the project node in Solution Explorer, point to Add, and then click Add Web Form.
In the Name box, type MySample.aspx, and then click Open.
2)In the Properties window, change the pageLayout property for the document to FlowLayout. Although you do not have to do this to use the sample code, this will make the presentation appear cleaner.
3)Add a DataGrid, a Button, and a Label server control to the page as follows:
Drag an ASP.NET DataGrid server control from the Web Forms toolbox onto the page.
In the Properties window, change the ID of the DataGrid control to DemoGrid.
Drag an ASP.NET Button server control from the Web Forms toolbox onto the page below the DataGrid.
In the Properties window, change the ID of the Button control to GetSelections, and then change the Text property to Get Selections.
Drag an ASP.NET Label server control from the Web Forms toolbox onto the page below the Button control.
In the Properties window, change the ID of the Label control to ResultsInfo, and then delete any text in the Text property.
4)Switch to HTML view in the editor. Add the code to the default DataGrid template to construct the columns. The resulting code for the control should appear as follows:
<asp:DataGrid id="DemoGrid" runat="server" DataKeyField="CustomerID">
<Columns>
<asp:TemplateColumn HeaderText="Customer">
<ItemTemplate>
<asp:CheckBox ID="myCheckbox" Runat="server" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

Labels:

Adding a CheckBox column to your DataGrid

Introduction
There are many articles that explain how to add controls to a DataGrid that can be used to represent and edit data in a format other than a common EditBox, however they all appear to require the programmer to edit the html in the .aspx page(s) rather than use code held solely in the .cs Codebehind files. I have in the past had to implement many different controls that can be used to represent and edit controls within a DataGrid and here I will demonstrate the CheckBox template column with bound CheckBoxes as it is one of the simplest but the the most used control other then the EditBox, and is used to edit fields that are of the boolean type.
ITemplate implementation
Before we can implement the class that will be used as a column within our DataGrid, a class that derives from ITemplate will need to be created that can be used for representing and or editing the data within the grid. In most cases a seperate class will need to be defined for displaying and editing, eg containing a label control or an edit box control. Fortunately we can use the same control, a CheckBox, to represent the boolean state as well as edit it.

public CheckBoxItem(bool editable)
{
readOnly = (editable==true)?false:true;
}
Handling the DataBinding event
Because the CheckBox control is to represent data that is held in the DataGrid then it will need to handle the DataBinding event, which will be called once for each row in the DataGrid. This can be set up in the InstantiateIn method implementation which is the one and only method of the ITemplate interface.

void ITemplate.InstantiateIn(Control container)
{
CheckBox box = new CheckBox();
box.DataBinding += new EventHandler(this.BindData);
container.Controls.Add(box);
}
Processing the DataBinding event
The handler for the DataBinding event is used to set the state of the control depending on the data within the underlying DataGrid as well as set the editable state depending on whether it is being used to view the data or edit the data.

public void BindData(object sender, EventArgs e)
{
CheckBox box = (CheckBox) sender;
DataGridItem container = (DataGridItem) box.NamingContainer;
box.Checked = false;
box.Enabled = (readOnly == true) ? false:true;
string data = ((DataRowView) container.DataItem)[dataField].ToString();
Type type = ((DataRowView)
container.DataItem).DataView.Table.Columns[dataField].DataType;
if (data.Length>0)
{
switch (type.ToString())
{
case "System.Boolean":
if ( data == "True")
{
box.Checked = true;
}
break;
default:
break;
}
}
}
CheckBox Template Column
The class that will be used as the column in our DataGrid will be derived from the System.Web.UI.WebControls.TemplateColumn class. We add objects of the above ITemplate implementation class to the ItemTemplate property, for display, and EditItemTemplate property, for editing.

public CheckBoxColumn()
{
// set the view one as readonly
viewItem = new CheckBoxItem(false);
this.ItemTemplate = viewItem as ITemplate;

// let the edit check box be editable
editItem = new CheckBoxItem(true);
this.EditItemTemplate = editItem as ITemplate;
}
Adding the Column to the DataGrid
The penultimate step is to add the column to the DataGrid itself. Because of the way we have designed the class this is simplicity itself as it can be used in place of a BoundColumn.

CheckBoxColumn checkCol = new CheckBoxColumn();
checkCol.HeaderText = "Boolean Field (Editable)";
checkCol.DataField = "Boolean";

...

DataGrid1.Columns.Add(checkCol);
Extracting the Updated State
The final step is extracting the data from the control itself when it comes to updating or inserting a row. Again we use a similar method as that normally employed however instead of a TextBox we use a CheckBox.

sqlUpdateCommand1.Parameters["@Boolean"].Value
= ((CheckBox)e.Item.Cells[4].Controls[0]).Checked;
AutoPostBack and receiving the CheckedChanged event
It was recently asked if it was possible to receive the CheckedChanged event from the CheckBoxes that were contained within the column. I have since updated the code to handle the scenario where you have a DataGrid with a CheckGridColumn and it is possible to update the field immediately.

Labels:

How to Adding a CheckBox Column to a DataGrid

To use the checkbox column in a DataGrid it's simply a matter of registering the tag at the top of the page:

<%@ Register TagPrefix="chkbox" Namespace="DataGridControls"
Assembly="DataGridCheckbox" %>
Then to add the checkbox column to the DataGrid:

<asp:DataGrid ID="dgTestGrid" Runat="server" AutoGenerateColumns=True
border="0" width="50%">
<Columns>
<chkbox:CheckBoxColumn/>
</Columns>
</asp:DataGrid>
The CheckBoxColumn class is pretty straight forward:

using System;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace DataGridControls
{
/// <summary>
/// CheckBoxColumn Derives from DataGrid Column
/// </summary>
public class CheckBoxColumn : DataGridColumn
{
public CheckBoxColumn(): base()
{
}

public override void InitializeCell(TableCell cell,
int columnIndex, ListItemType itemType)
{
//let the base class initialize the cell
base.InitializeCell(cell, columnIndex, itemType);



//we don't want to add a checkbox to the header.
if( itemType == ListItemType.EditItem ||
itemType == ListItemType.Item ||
itemType == ListItemType.AlternatingItem ||
itemType == ListItemType.SelectedItem){

HtmlInputCheckBox checkbox = new HtmlInputCheckBox();
//assign an ID that we can use to find the control later
checkbox.ID = "checkboxCol";
cell.Controls.Add(checkbox);
}
}
public Int32[] SelectedIndexes
{
get
{
ArrayList selectedIndexList = new ArrayList();
//iterate each DataGridItem and find our checkbox
foreach( DataGridItem item in this.Owner.Items )
{
HtmlInputCheckBox chkBox =
(HtmlInputCheckBox) item.FindControl("checkboxCol");

//If it's selected then add it to our ArrayList
if ( chkBox != null && chkBox.Checked )
{
selectedIndexList.Add( item.ItemIndex );
}

}
return (Int32[])selectedIndexList.ToArray(typeof(
System.Int32 ) );
}
}
public object[] SelectedDataKeys
{
get
{
//Just iterate each of the selectedindexes and
//match it up to the datakey field
ArrayList dataKeyList = new ArrayList();
//make sure the datakeys have some values
if(this.Owner.DataKeys.Count > 0)
{
foreach( Int32 selectedIndex in SelectedIndexes )
{

object DataKey =
(this.Owner.DataKeys[selectedIndex].ToString());
dataKeyList.Add(DataKey);
}
}
return (object[])dataKeyList.ToArray(typeof( object ) );
}

}
}
}
The class exposes 2 properties:
SelectedDataKeys: Returns an ArrayList with the DataKey values
SelectedIndexes: Returns an Int32[] with the selectedIndex values
To find out which checkbox has been selected:

//On our button's Onclick

protected void btnSubmit_Click(object sender, EventArgs e)
{
//Get our checkboxcolumn, we know it's position is 0
CheckBoxColumn chkbox = (CheckBoxColumn) dgTestGrid.Columns[0];

foreach(object datakeyfield in chkbox.SelectedDataKeys)
{
Response.Write(datakeyfield.ToString() + "<br>");
}
}
That's pretty much it, the DataKeyField of the DataGrid can be of any type. The sample I've included binds a DataTable to the DataGrid, you can change the DataKeyField from "ID" (int) to "Name" (string) to see the code working with different types.

Labels:

How to Including a CheckBox Control Inside an ASP.NET DataGrid

CheckBox controls are very easy to add to a DataGrid. All you have to do is create a TemplateColumn and then add the CheckBox much as you would on an aspx page. The real trick is, in your code, to be able to find the CheckBox controls and find out whether or not they are checked and then do something with that information.
Please read through the .aspx page shown below. It is pretty straight ahead, but there are several things you should notice. First, there is a button control near the top. The button is used to call a subroutine in the code-behind page whose purpose is to accomplish a (mock) delete of the checked rows.
The next thing to notice is the DataGrid itself. You may notice that it contains a mixture of TemplateColumns and BoundColumns. We will be using the FindControl method in the code-behind page so some of the data columns in the grid are displayed in label controls. To do this we need to use asp:TemplateColumns. The columns we will be accessing in the code-behind page are CompanyName, CustomerID, and the CheckBox controls themselves. These three columns are displayed in labels withing TemplateColumns. The other columns are just for simply displaying data so to save a lot of typing I just used BoundColumns. Yes, you are allowed to mix and match control types within a single datagrid!
The last thing to notice about the grid is that we have included an invisible column. If we are going to delete rows we really need a unique key to be save. CustomerID is such a key. We could have displayed it, but decided not to just for grins. We could have made it simply an invisible label within another TemplateColumn, and this would work just as well, but we wanted to demonstrate another technique by making it a column of its own, but hiding it from view.
Near the bottom of the page there is a label control to display information about the checkboxes that were checked by the user. Its text is created by the code-behind subroutine called by the button at the top of the page.

<%@ Page Language="vb" Src="ChkBoxDataGrid.aspx.vb" Inherits="DotNetJohn.ChkBoxDataGrid" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD html 4.0 Transitional//EN">
<html>
<head>
<title>ChkBoxDataGrid</title>
<meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
<meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
<meta name=vs_defaultClientScript content="JavaScript">
<meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5">
</head>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<asp:Button ID="btnShow" Text="Delete Checked Rows" OnClick="ShowSelections" Runat="server" />
<p></p>
<asp:DataGrid ID="dtgCusts" Runat="server"
AutoGenerateColumns="False"
BorderColor="#999999"
BorderStyle="None"
BorderWidth="1px"
BackColor="White"
CellPadding="3"
GridLines="Vertical">
<Columns>
<asp:TemplateColumn HeaderText="Company Name">
<ItemTemplate>
<asp:Label ID="lblCompanyName"
Text='<%# DataBinder.Eval(Container.DataItem,"CompanyName") %>'
runat="server" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn HeaderText="Contact Name" DataField="ContactName" />
<asp:BoundColumn HeaderText="Contact Title" DataField="ContactTitle" />
<asp:BoundColumn HeaderText="City" DataField="City" />
<asp:BoundColumn HeaderText="Country" DataField="Country" />
<asp:BoundColumn HeaderText="Telephone" DataField="Phone" />
<asp:BoundColumn HeaderText="Customer ID" DataField="CustomerID" Visible="False" />
<asp:TemplateColumn HeaderText="CustomerID" Visible="False">
<ItemTemplate>
<asp:Label ID="lblCustomerID"
Text='<%# DataBinder.Eval(Container.DataItem,"CustomerID") %>'
Runat="server" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Delete" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkSelection" Runat="server" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
<AlternatingItemStyle BackColor="#DCDCDC" />
<ItemStyle ForeColor="Black" BackColor="#EEEEEE" />
<headerStyle Font-Bold="True" ForeColor="White" BackColor="#000084" />
</asp:DataGrid>
<asp:Label ID="lblSelections"
Runat="server"
Font-Name="Verdana"
Font-Size="10px" />
</form>
</body>
</html>
Now for the code-behind page which is shown in two sections below. The first section is, for the most part, just the usual database access and binding of the DataGrid. One thing you might notice in the the Page_Load event is an ...Attributes.Add... line. This adds a JavaScript confirm box to our button on the aspx page. You haven't seen this before you may find it handy from time to time.

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.UI.WebControls

Namespace DotNetJohn

Public Class ChkBoxDataGrid : Inherits System.Web.UI.Page
Protected btnShow As Button
Protected dtgCusts As DataGrid
Protected lblSelections As Label

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not IsPostBack Then
btnShow.Attributes.Add("onClick", "javascript:return confirm('Are you sure you want to delete these rows?')")
BindTheData
End If
End Sub

Sub BindTheData
Dim objConn As SqlConnection
Dim objCmd As SqlCommand
objConn = New SqlConnection(ConfigurationSettings.AppSettings("NorthwindConnection"))
Dim strSql As String
strSql = "SELECT Top 10 CustomerID, CompanyName, ContactName, " _
& "ContactTitle, City, Country, Phone FROM Customers"
Try
objCmd = New SqlCommand(strSql, objConn)
objConn.Open
dtgCusts.DataSource = objCmd.ExecuteReader()
dtgCusts.DataBind()
Catch
Finally
If objConn.State = ConnectionState.Open Then
objConn.Close()
objConn.Dispose()
End If
End Try
End Sub


It is in this last section of code that we come to the meat of the article. It was very easy to add CheckBoxes to the DataGrid in our aspx page. Now how do we find out which ones were checked and information we need from the rows on which checked boxes are found? The answer lies in the DataGrid's item collection and in the FindControl method. As you can see we are dimensioning a variable (dgItem) as DataGridItem. DataGridItem is part of the System.Web.UI.WebControls namespace. Using the this variable we can use a For Each loop to cycle through each row in the grid. We have also dimensioned chkSelected as CheckBox. This allows us to find controls of type CheckBox. We do this with the line chkSelected = dgItem.FindControl("chkSelection"). "chkSelection" is the name we gave our CheckBoxes when we created them inside the grid in our aspx page. Once our code finds a chkSelection we can then test to see if it is checked. If it is checked, then we again use FindControl to find the other information we need such as CustomerID and Company Name. If we were really deleting rows in this example program we could then use CustomerID to write a SQL DELETE statement with CustomerID in the WHERE clause. Instead, we are just displaying Company Name and CustomerID in the label control on the aspx page.

Sub ShowSelections(sender As System.Object, e As System.EventArgs)
Dim dgItem As DataGridItem
Dim chkSelected As CheckBox
Dim strCompanyName As String
Dim strCustomerID As String

lblSelections.Text = "<br>Fooled Ya! The following rows were marked for deletion, "
lblSelections.Text += "but not actually deleted:<br><br>"
For Each dgItem in dtgCusts.Items
chkSelected = dgItem.FindControl("chkSelection")
If chkSelected.Checked Then
strCompanyName = CType(dgItem.FindControl("lblCompanyName"), Label).Text
strCustomerID = CType(dgItem.FindControl("lblCustomerId"), Label).Text
lblSelections.Text += "Company Name: <b>" & strCompanyName & "</b> | "
lblSelections.Text += "Customer ID: <b>" & strCustomerID & "</b><br>"
End If
Next
End Sub

End Class

End Namespace



==============================

Check All CheckBoxes in an ASP.NET DataGrid Using a Single CheckBox
Do you have any DataGrids in your ASP.NET application with a CheckBox for each row? If so, you may have wanted a faster way to check or uncheck all items. One way uses a single CheckBox in the header or footer of that DataGrid. This tip shows you how.
First, create a JavaScript file for your application, which includes the following function:

FormFunctions.js
..
//checks all DataGrid CheckBoxes with the given name with the given
value
function CheckAllDataGridCheckBoxes(aspCheckBoxID, checkVal) {

re = new RegExp(':' + aspCheckBoxID + '$') //generated control
name starts with a colon

for(i = 0; i < document.forms[0].elements.length; i++) {

elm = document.forms[0].elements[i]

if (elm.type == 'checkbox') {

if (re.test(elm.name)) {

elm.checked = checkVal

}
}
}
}
..
The script takes the name of the DataGrid CheckBox to be checked and the value to apply (checked or unchecked).
In your .aspx file, you need to include the JavaScript file as follows:

MyForm.aspx
..
<HTML>
<HEAD>
...
<script language="javascript"
src="/MyWebApp/MyUtils/FormFunctions.js"></script>
...
</HEAD>
..
Finally, add the CheckBox to your DataGrid, including a call to the script in the onclick event:

MyForm.aspx
..
<Columns>
<asp:TemplateColumn>
<HeaderTemplate>
<input id="chkAllItems" type="checkbox"
onclick="CheckAllDataGridCheckBoxes('chkItemChecked',
document.forms[0].chkAllItems.checked)" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox id="chkItemChecked"
runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>
..
Notice that the call to the JavaScript function passes in the name of the CheckBox appearing on each row and the value of the check all CheckBox.

Labels:

How DataGrid has built-in Column Sorting functionality

Getting and Displaying the Data
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<head>
<title>DotNetJunkies.com - Column Sorting in the DataGrid</title>
<script runat="server" language="VB">
Protected _sqlStmt As String = "SELECT CompanyName, ContactName, ContactTitle, Phone, Fax FROM Customers"

Sub Page_Load(Source As Object, E As EventArgs)
If Not Page.IsPostBack Then
BindData()
End If
End Sub

Sub BindData()
DimconStringAsString="server=localhost;database=Northwind;uid=sa;pwd=;"
Dim myDataSet As New DataSet
Dim myDataAdapter As New SqlDataAdapter(_sqlStmt, conString)
myDataAdapter.Fill(myDataSet, "Customers")
myDataGrid.DataSource = myDataSet.Tables("Customers")
myDataGrid.DataBind()
End Sub
</script>
<style>
.DataGrid {font:x-small Verdana, Arial, sans-serif}
</style>
</head>
<body>
<form runat="server" method="post">
<asp:DataGrid runat="server" id="myDataGrid"
Border="0"
Cellpadding="4"
Cellspacing="0"
AlternatingItemStyle-BackColor="#EFEFEF"
ShowHeader="True"
CssClass="DataGrid"
HeaderStyle-BackColor="Black"
HeaderStyle-ForeColor="White"
HeaderStyle-Font-Bold="True"
/>
</form>
</body>
</html>
The Revised DataGrid Properties
<asp:DataGrid runat="server" id="myDataGrid"
Border="0"
Cellpadding="4"
Cellspacing="0"
AlternatingItemStyle-BackColor="#EFEFEF"
ShowHeader="True"
CssClass="DataGrid"
HeaderStyle-BackColor="Black"
HeaderStyle-ForeColor="White"
HeaderStyle-Font-Bold="True"
AllowSorting="True"
OnSortCommand="SortCommand_OnClick"
/>
The SortCommand_OnClick() Event Handler
Sub SortCommand_OnClick(Source As Object, E As DataGridSortCommandEventArgs)
_sqlStmt = _sqlStmt & " ORDER BY " & E.SortExpression
BindData()
End Sub
Column Sorting and Paging Together
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<head>
<title>ASPNextGen.com - Column Sorting in the DataGrid</title>
<script runat="server" language="VB">
Protected _sqlStmt As String = "SELECT CompanyName, ContactName, ContactTitle, Phone, Fax FROM Customers"

Sub Page_Load(Source As Object, E As EventArgs)
If Not Page.IsPostBack Then
SQLStatement.Text = _sqlStmt
BindData()
End If
End Sub

Sub BindData()
Dim myDataSet As New DataSet
DimConStringAsString="server=localhost;database=Northwind;uid=sa;pwd=;"
Dim myDataAdapter As New SqlDataAdapter(SQLStatement.Text, ConString)
myDataAdapter.Fill(myDataSet, "Customers")
myDataGrid.DataSource = myDataSet.Tables("Customers")
myDataGrid.DataBind()
End Sub

Sub PageIndexChanged_OnClick(Source As Object, E As DataGridPageChangedEventArgs)
myDataGrid.CurrentPageIndex = E.NewPageIndex
BindData()
End Sub

Sub SortCommand_OnClick(Source As Object, E As DataGridSortCommandEventArgs)
SQLStatement.Text = _sqlStmt & " ORDER BY " & E.SortExpression
BindData()
End Sub
</script>
<style>
.DataGrid {font:x-small Verdana, Arial, sans-serif}
</style>
</head>
<body>
<form runat="server" method="post">
<asp:Label id="SQLStatement" runat="server" Visible="False" />
<asp:DataGrid runat="server" id="myDataGrid"
Border="0"
Cellpadding="4"
Cellspacing="0"
AlternatingItemStyle-BackColor="#EFEFEF"
ShowHeader="True"
CssClass="DataGrid"
HeaderStyle-BackColor="Black"
HeaderStyle-ForeColor="White"
HeaderStyle-Font-Bold="True"
AllowSorting="True"
OnSortCommand="SortCommand_OnClick"
AllowPaging="True"
OnPageIndexChanged="PageIndexChanged_OnClick"
PageSize="10"
PagerStyle-Mode="NumericPages"
PagerStyle-HorizontalAlign="Right"
/>
</form>
</body>
</html>

Labels:

How to Setting Datagrid column formatting in code

private string setFormating(DataColumn bc)
{
string dataType = null;
switch(bc.DataType.ToString())
{
case "System.Int32":
dataType = "{0:#,###}";
break;
case "System.Decimal":
dataType = "{0:c}";
break;
case "System.DateTime":
dataType="{0:dd-mm-yyyy}";
break;
case "System.String":
dataType="";
break;
default:
dataType = "";
break;
}
return dataType;
}

Labels:

How to Add Columns to a datagrid dynamically in the code behind

DataGrid1.AutoGenerateColumns=false;
BoundColumn column = new BoundColumn();
column.DataField = c.ColumnName;
column.HeaderText = c.ColumnName.Replace("_"," ");
column.DataFormatString =setFormating(c);
return column;

Labels:

How to Setting Datagrid properties in code

DataGrid1.Width = 600;
DataGrid1.Height= 400;
DataGrid1.GridLines = GridLines.Both;
DataGrid1.CellPadding =1;
DataGrid1.ForeColor=System.Drawing.Color.Black;
DataGrid1.BackColor = System.Drawing.Color.Beige;
DataGrid1.AlternatingItemStyle.BackColor = System.Drawing.Color.Gainsboro;
DataGrid1.HeaderStyle.BackColor = System.Drawing.Color.Brown;

Labels:

How to Create a datagrid programatically

// Instantiate the data grid control
System.Web.UI.WebControls.DataGrid DataGrid1 =
new System.Web.UI.WebControls.DataGrid();
// the GetDataSet method executes the Stored procedure and populates a dataset ds
ds = GetDataSet("DynamicDataGridSP1");
// the dataset is used as the data source for our newly created datatrid DataGrid1
DataGrid1.DataSource=ds;
DataGrid1.DataBind();
// DataGrid1 is added to the PlaceHolder
PlaceHolder.Controls.Add(DataGrid1);

Labels: