Tuesday, January 3, 2012

Create, Insert, Search, Delete in DataTable

Create DataTable and Define its Fields (Cloumns)
DataTable dt = new DataTable();

dt.Columns.Add("Category_Name", typeof(string));

Fetch Data from DataBase and Insert into DataTable

DataSet dstmp = new DataSet();
query = "SELECT  *  FROM  vw_ItemDet";

SqlDataAdapter adp = new SqlDataAdapter(query, con);
dt = dstmp.Tables[0];

Insert Data from WebForm -:

 DataTable dt = (DataTable)ViewState["Dt"];
 DataRow dtdr = dt.NewRow();
 dtdr["Qty"] = txtQty.Text;

Store values of DataTable in  ViewState for further use.Basically its helpful if you have to use  this table value later.

ViewState["dtable"] = dt;

Retrieve value from ViewState

DataTable VWTempDTable=new DataTable();
VWTempDTable = (DataTable)ViewState["dtable"];

Insert Values from one DataTable to Another based on some condition..-:
string cond = "Category_Name='" + ViewState["sad"] + "'";
DataRow[] foundRows;
foundRows = VWTempDTable.Select(cond);
foreach (DataRow row in foundRows)
            VWTempSecond.ImportRow(row); ///VWTempSecond is another DataTable

Delete Rows from DataTable -:


1 comment:

  1. Insert Data from WebForm

    NullReferenceException: Object reference not set to an instance of an object for DataRow