Wednesday, December 02, 2009

Gridview row deleting in C#

Steps to delete a row in Grid view programmatic which bind with real time database table.
1,In Grid view server control must be set to false of AutoGenerateColumns
2,Make Columns tag to list the user defined column header on the asp.net page.
just like the following

  
DataKeyNames="ProductID" SelectedIndex="1"
onselectedindexchanged="GridView1_SelectedIndexChanged"
onrowcommand="GridView1_RowCommand" AutoGenerateColumns="false">








3,Set to DataKeyNames value to Table's primary key like
  
DataKeyNames="ProductID" SelectedIndex="1"
onselectedindexchanged="GridView1_SelectedIndexChanged"
onrowcommand="GridView1_RowCommand" AutoGenerateColumns="false">


An event named "onrowcommand" triggered on the Grid view deletion of the selected row must be deleted from the table.

Here I used the filter CommandName and commandArgument to check whether the deletion link button which attached the GridView clicked.


protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Remove")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];

Database db = DatabaseFactory.CreateDatabase("DatabaseConnectionString");
DbCommand cmd = db.GetSqlStringCommand("DELETE from Products where ProductID='" + row.Cells[1].Text.ToString() + "'");
db.ExecuteNonQuery(cmd);
GridView1.DataSource = ShowProductDetail();
GridView1.DataBind();

}

}


I used Microsoft Enterprise Library 4.1 in my example to deal with database and its related operation.Its based on SQLExpress database.
  



Thursday, November 26, 2009

script test

  



Sunday, November 15, 2009

Convert DataSet into ArrayList in C#

Converting the DataSet into ArrayList is not an big deal anymore.
If you are sure about the number of columns in the DataTable,create the same class members in the Class.

Let assume I have an DataSet contains of the table named "Product" which has three columns called ProductID and Stock.

First step to convert the DataSet into ArrayList is,creating the Class name ProductClass



Database db = DatabaseFactory.CreateDatabase("DatabaseConnectionString");
DbCommand cmd = db.GetSqlStringCommand("Select * from Products");
DataSet ds = db.ExecuteDataSet(cmd);
List proList = new List();

for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Products p = new Products();
p.ProductName = ds.Tables[0].Rows[i]["ProductName"].ToString();
p.ProductID = ds.Tables[0].Rows[i]["ProductID"].ToString();
proList.Add(p);

}


Product.cs

public class Products
{
private string _productName;

private string _productid;

public string ProductName
{
get { return _productName; }
set { _productName = value; }


}

public string ProductID
{
get { return _productid; }
set { _productid = value; }

}



}

GridView1.DataSource = proList.ToArray();
GridView1.DataBind();