Showing posts with label Search. Show all posts
Showing posts with label Search. Show all posts

Tuesday, July 15, 2014

Create, Insert, Search, Delete in DataTable


//Create DataTable and Define its Fields (Cloumns)
DataTable dt = new DataTable();
dt.Columns.Add("ItemId",typeof(int));
dt.Columns.Add("Item",typeof(string));
dt.Columns.Add("Qty",typeof(float));
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);
adp.Fill(dstmp);
dt = dstmp.Tables[0];

//Insert Data from WebForm -:

 DataTable dt = (DataTable)ViewState["Dt"];
 DataRow dtdr = dt.NewRow();
 dtdr["ItemId"]=ddlOtherItem.SelectedValue;
 dtdr["Item"]=ddlOtherItem.SelectedItem.Text;
 dtdr["Qty"] = txtQty.Text;
 dt.Rows.Add(dtdr);

//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 -:

VWTempSecond.Rows[Convert.ToInt32(s)].Delete();