I have Gridview,As see in attachment-
on GridViewProducts_RowCommand Event,When the user clicks on Add To Cart,Then the datatable is creaated & data of that row is added to datatable,When the user clicks on Add To cart for second time,Then the data is similarly added to Data table..
When the user do all shopping,then click on BUtton & then Data from datatable is inserted into DB...
public partial class AddProductsToCart : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection("Data Source=SONIA-B408A4159\\SQLEXPRESS;Initial catalog=sonia;Integrated Security=true");
bool IsDataTableCreated;
DataTable MyNewDataTable =new DataTable() ;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
IsDataTableCreated = false;
}
}
protected void GridViewProducts_RowCommand(object sender, GridViewCommandEventArgs e)
{
string sProductName;
if (e.CommandName =="AddToCart")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridViewProducts.Rows[index];
sProductName = row.Cells[1].Text;
if (IsDataTableCreated == false)
{
MyNewDataTable = CreateDataTable();
IsDataTableCreated =true ;
}
AddDataToTable(id);
}
}
private DataTable CreateDataTable()
{
DataTable myDataTable = new DataTable();
DataColumn myDataColumn;
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "productname;
myDataTable.Columns.Add(myDataColumn);
return myDataTable;
}
private void AddDataToTable(string productname)
{
DataRow row;
row = MyNewDataTable.NewRow();
row["productname"] = productname;
MyNewDataTable.Rows.Add(row);
int rows = MyNewDataTable.Rows.Count;
}
protected void btnAddWholeDataToDatabase_Click(object sender, EventArgs e)
{
int rows = MyNewDataTable.Rows.Count;
foreach (DataRow dr in MyNewDataTable.Rows)
{
string col1 = dr["productname"].ToString();
}
}
}
I have taken bool variable IsDataTableCreated,Set it to false on form_load,means that data table is not created, ,So that when the user first time clicks on ADd To Cart,Datatable is created & Data is insrted.. & I set it to true...
In procedure AddDataToTable line
int rows = MyNewDataTable.Rows.Count;
WHen the procedure is called,in variabe rows 1 is there...
I m facind two probs in mine code-
1) I put the cond if (IsDataTableCreated == false), only then the datatable is created,..But each time user clciks on Add To cart..Control goes inside the loop.
2) When I click on btnAddWholeDataToDatabase_Click,there are no rows in datatable.Y So???????/