c# Counter requires 2 button clicks to update - c#

I have a problem that has been bugging me all day.
In my code I have the following:
private int rowCount
{
get { return (int)ViewState["rowCount"]; }
set { ViewState["rowCount"] = value; }
}
and a button event
protected void addRow_Click(object sender, EventArgs e)
{
rowCount = rowCount + 1;
}
Then on Page_Load I read that value and create controls accordingly.
I understand the button event fires AFTER the Page_Load fires so the value isn't updated until the next postback. Real nightmare.
Here's the entire code:
protected void Page_Load(object sender, EventArgs e)
{
string xmlValue = ""; //To read a value from a database
if (xmlValue.Length > 0)
{
if (!Page.IsPostBack)
{
DataSet ds = XMLToDataSet(xmlValue);
Table dimensionsTable = DataSetToTable(ds);
tablePanel.Controls.Add(dimensionsTable);
DataTable dt = ds.Tables["Dimensions"];
rowCount = dt.Rows.Count;
colCount = dt.Columns.Count;
}
else
{
tablePanel.Controls.Add(DataSetToTable(DefaultDataSet(rowCount, colCount)));
}
}
else
{
if (!Page.IsPostBack)
{
rowCount = 2;
colCount = 4;
}
tablePanel.Controls.Add(DataSetToTable(DefaultDataSet(rowCount, colCount)));
}
}
protected void submit_Click(object sender, EventArgs e)
{
resultsLabel.Text = Server.HtmlEncode(DataSetToStringXML(TableToDataSet((Table)tablePanel.Controls[0])));
}
protected void addColumn_Click(object sender, EventArgs e)
{
colCount = colCount + 1;
}
protected void addRow_Click(object sender, EventArgs e)
{
rowCount = rowCount + 1;
}
public DataSet TableToDataSet(Table table)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("Dimensions");
ds.Tables.Add(dt);
//Add headers
for (int i = 0; i < table.Rows[0].Cells.Count; i++)
{
DataColumn col = new DataColumn();
TextBox headerTxtBox = (TextBox)table.Rows[0].Cells[i].Controls[0];
col.ColumnName = headerTxtBox.Text;
col.Caption = headerTxtBox.Text;
dt.Columns.Add(col);
}
for (int i = 0; i < table.Rows.Count; i++)
{
DataRow valueRow = dt.NewRow();
for (int x = 0; x < table.Rows[i].Cells.Count; x++)
{
TextBox valueTextBox = (TextBox)table.Rows[i].Cells[x].Controls[0];
valueRow[x] = valueTextBox.Text;
}
dt.Rows.Add(valueRow);
}
return ds;
}
public Table DataSetToTable(DataSet ds)
{
DataTable dt = ds.Tables["Dimensions"];
Table newTable = new Table();
//Add headers
TableRow headerRow = new TableRow();
for (int i = 0; i < dt.Columns.Count; i++)
{
TableCell headerCell = new TableCell();
TextBox headerTxtBox = new TextBox();
headerTxtBox.ID = "HeadersTxtBox" + i.ToString();
headerTxtBox.Font.Bold = true;
headerTxtBox.Text = dt.Columns[i].ColumnName;
headerCell.Controls.Add(headerTxtBox);
headerRow.Cells.Add(headerCell);
}
newTable.Rows.Add(headerRow);
//Add value rows
for (int i = 0; i < dt.Rows.Count; i++)
{
TableRow valueRow = new TableRow();
for (int x = 0; x < dt.Columns.Count; x++)
{
TableCell valueCell = new TableCell();
TextBox valueTxtBox = new TextBox();
valueTxtBox.ID = "ValueTxtBox" + i.ToString() + i + x + x.ToString();
valueTxtBox.Text = dt.Rows[i][x].ToString();
valueCell.Controls.Add(valueTxtBox);
valueRow.Cells.Add(valueCell);
}
newTable.Rows.Add(valueRow);
}
return newTable;
}
public DataSet DefaultDataSet(int rows, int cols)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("Dimensions");
ds.Tables.Add(dt);
DataColumn nameCol = new DataColumn();
nameCol.Caption = "Name";
nameCol.ColumnName = "Name";
nameCol.DataType = System.Type.GetType("System.String");
dt.Columns.Add(nameCol);
DataColumn widthCol = new DataColumn();
widthCol.Caption = "Width";
widthCol.ColumnName = "Width";
widthCol.DataType = System.Type.GetType("System.String");
dt.Columns.Add(widthCol);
if (cols > 2)
{
DataColumn heightCol = new DataColumn();
heightCol.Caption = "Height";
heightCol.ColumnName = "Height";
heightCol.DataType = System.Type.GetType("System.String");
dt.Columns.Add(heightCol);
}
if (cols > 3)
{
DataColumn depthCol = new DataColumn();
depthCol.Caption = "Depth";
depthCol.ColumnName = "Depth";
depthCol.DataType = System.Type.GetType("System.String");
dt.Columns.Add(depthCol);
}
if (cols > 4)
{
int newColCount = cols - 4;
for (int i = 0; i < newColCount; i++)
{
DataColumn newCol = new DataColumn();
newCol.Caption = "New " + i.ToString();
newCol.ColumnName = "New " + i.ToString();
newCol.DataType = System.Type.GetType("System.String");
dt.Columns.Add(newCol);
}
}
for (int i = 0; i < rows; i++)
{
DataRow newRow = dt.NewRow();
newRow["Name"] = "Name " + i.ToString();
newRow["Width"] = "Width " + i.ToString();
if (cols > 2)
{
newRow["Height"] = "Height " + i.ToString();
}
if (cols > 3)
{
newRow["Depth"] = "Depth " + i.ToString();
}
dt.Rows.Add(newRow);
}
return ds;
}
public DataSet XMLToDataSet(string xml)
{
StringReader sr = new StringReader(xml);
DataSet ds = new DataSet();
ds.ReadXml(sr);
return ds;
}
public string DataSetToStringXML(DataSet ds)
{
XmlDocument _XMLDoc = new XmlDocument();
_XMLDoc.LoadXml(ds.GetXml());
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
XmlDocument xml = _XMLDoc;
xml.WriteTo(xw);
return sw.ToString();
}
private int rowCount
{
get { return (int)ViewState["rowCount"]; }
set { ViewState["rowCount"] = value; }
}
private int colCount
{
get { return (int)ViewState["colCount"]; }
set { ViewState["colCount"] = value; }
}
EDIT: Here's my .aspx as well in case you want to try it out in VS.
<asp:Panel ID="tablePanel" runat="server" CssClass="table-panel" />
<asp:Label ID="resultsLabel" runat="server" />
<asp:LinkButton ID="submit" Text="submit" runat="server" onclick="submit_Click" />
<asp:LinkButton ID="addColumn" Text="Add Column" runat="server"
onclick="addColumn_Click" />
<asp:LinkButton ID="addRow" Text="Add Row" runat="server" onclick="addRow_Click" />
Thanks in advance,
Marko

Just as I recommended in this other question, if you'd like some page logic to execute AFTER the buttons' Click event, put that code into the Page_PreRender instead.
You can read more about it here: ASP.NET page life cycle.
EDIT:
After examining your code more closely, I see that you add stuff and create new controls, which is not a good idea in the PreRender event.
Instead, put the code into a separate method. In the Page_Load, check if it is a postback and handle the case when it isn't.
In the buttons' click evnt, also add a call to that new method. (thus handling the IsPostback == true case)

OK I've solved the problem by following instructions in this post.
Here's my final code - feel free to use it if you ever need to create dynamic controls based on a counter.
Also I wouldn't mind feedback on the overall coding style, I always appreciate others' input.
protected void Page_Load(object sender, EventArgs e)
{
string xmlValue = ""; //To read a value from a database
if (xmlValue.Length > 0)
{
if (!Page.IsPostBack)
{
DataSet ds = XMLToDataSet(xmlValue);
Table dimensionsTable = DataSetToTable(ds);
tablePanel.Controls.Add(dimensionsTable);
DataTable dt = ds.Tables["Dimensions"];
rowCount = dt.Rows.Count;
colCount = dt.Columns.Count;
}
else
{
tablePanel.Controls.Add(DataSetToTable(DefaultDataSet(rowCount, colCount)));
}
}
else
{
if (!Page.IsPostBack)
{
rowCount = 2;
colCount = 4;
}
else
{
if (GetPostBackControl(this.Page).ID == "addRow")
{
rowCount = rowCount + 1;
}
else if (GetPostBackControl(this.Page).ID == "addColumn")
{
colCount = colCount + 1;
}
}
tablePanel.Controls.Add(DataSetToTable(DefaultDataSet(rowCount, colCount)));
}
}
protected void submit_Click(object sender, EventArgs e)
{
resultsLabel.Text = Server.HtmlEncode(DataSetToStringXML(TableToDataSet((Table)tablePanel.Controls[0])));
}
protected void addColumn_Click(object sender, EventArgs e)
{
}
protected void addRow_Click(object sender, EventArgs e)
{
}
public DataSet TableToDataSet(Table table)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("Dimensions");
ds.Tables.Add(dt);
//Add headers
for (int i = 0; i < table.Rows[0].Cells.Count; i++)
{
DataColumn col = new DataColumn();
TextBox headerTxtBox = (TextBox)table.Rows[0].Cells[i].Controls[0];
col.ColumnName = headerTxtBox.Text;
col.Caption = headerTxtBox.Text;
dt.Columns.Add(col);
}
for (int i = 0; i < table.Rows.Count; i++)
{
DataRow valueRow = dt.NewRow();
for (int x = 0; x < table.Rows[i].Cells.Count; x++)
{
TextBox valueTextBox = (TextBox)table.Rows[i].Cells[x].Controls[0];
valueRow[x] = valueTextBox.Text;
}
dt.Rows.Add(valueRow);
}
return ds;
}
public Table DataSetToTable(DataSet ds)
{
DataTable dt = ds.Tables["Dimensions"];
Table newTable = new Table();
//Add headers
TableRow headerRow = new TableRow();
for (int i = 0; i < dt.Columns.Count; i++)
{
TableCell headerCell = new TableCell();
TextBox headerTxtBox = new TextBox();
headerTxtBox.ID = "HeadersTxtBox" + i.ToString();
headerTxtBox.Font.Bold = true;
headerTxtBox.Text = dt.Columns[i].ColumnName;
headerCell.Controls.Add(headerTxtBox);
headerRow.Cells.Add(headerCell);
}
newTable.Rows.Add(headerRow);
//Add value rows
for (int i = 0; i < dt.Rows.Count; i++)
{
TableRow valueRow = new TableRow();
for (int x = 0; x < dt.Columns.Count; x++)
{
TableCell valueCell = new TableCell();
TextBox valueTxtBox = new TextBox();
valueTxtBox.ID = "ValueTxtBox" + i.ToString() + i + x + x.ToString();
valueTxtBox.Text = dt.Rows[i][x].ToString();
valueCell.Controls.Add(valueTxtBox);
valueRow.Cells.Add(valueCell);
}
newTable.Rows.Add(valueRow);
}
return newTable;
}
public DataSet DefaultDataSet(int rows, int cols)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("Dimensions");
ds.Tables.Add(dt);
DataColumn nameCol = new DataColumn();
nameCol.Caption = "Name";
nameCol.ColumnName = "Name";
nameCol.DataType = System.Type.GetType("System.String");
dt.Columns.Add(nameCol);
DataColumn widthCol = new DataColumn();
widthCol.Caption = "Width";
widthCol.ColumnName = "Width";
widthCol.DataType = System.Type.GetType("System.String");
dt.Columns.Add(widthCol);
if (cols > 2)
{
DataColumn heightCol = new DataColumn();
heightCol.Caption = "Height";
heightCol.ColumnName = "Height";
heightCol.DataType = System.Type.GetType("System.String");
dt.Columns.Add(heightCol);
}
if (cols > 3)
{
DataColumn depthCol = new DataColumn();
depthCol.Caption = "Depth";
depthCol.ColumnName = "Depth";
depthCol.DataType = System.Type.GetType("System.String");
dt.Columns.Add(depthCol);
}
if (cols > 4)
{
int newColCount = cols - 4;
for (int i = 0; i < newColCount; i++)
{
DataColumn newCol = new DataColumn();
newCol.Caption = "New " + i.ToString();
newCol.ColumnName = "New " + i.ToString();
newCol.DataType = System.Type.GetType("System.String");
dt.Columns.Add(newCol);
}
}
for (int i = 0; i < rows; i++)
{
DataRow newRow = dt.NewRow();
newRow["Name"] = "Name " + i.ToString();
newRow["Width"] = "Width " + i.ToString();
if (cols > 2)
{
newRow["Height"] = "Height " + i.ToString();
}
if (cols > 3)
{
newRow["Depth"] = "Depth " + i.ToString();
}
dt.Rows.Add(newRow);
}
return ds;
}
public DataSet XMLToDataSet(string xml)
{
StringReader sr = new StringReader(xml);
DataSet ds = new DataSet();
ds.ReadXml(sr);
return ds;
}
public string DataSetToStringXML(DataSet ds)
{
XmlDocument _XMLDoc = new XmlDocument();
_XMLDoc.LoadXml(ds.GetXml());
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
XmlDocument xml = _XMLDoc;
xml.WriteTo(xw);
return sw.ToString();
}
private int rowCount
{
get { return (int)ViewState["rowCount"]; }
set { ViewState["rowCount"] = value; }
}
private int colCount
{
get { return (int)ViewState["colCount"]; }
set { ViewState["colCount"] = value; }
}
public static Control GetPostBackControl(Page page)
{
Control control = null;
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
if (ctrlname != null && ctrlname != string.Empty)
{
control = page.FindControl(ctrlname);
}
else
{
foreach (string ctl in page.Request.Form)
{
Control c = page.FindControl(ctl);
if (c is System.Web.UI.WebControls.Button)
{
control = c;
break;
}
}
}
return control;
}

move this code:
tablePanel.Controls.Add(DataSetToTable(DefaultDataSet(rowCount, colC....
To the prerender event to make the table bind to its data after the button click fired.

Related

generate datagrid row based on textbox input

how do you generate datagrid row based on user's input on the web, so if i input 5 on textbox then 5 rows will be generated vice versa.
i have tried this code of mine below but i keep on getting Exception of type 'System.OutOfMemoryException' was thrown error everytime i try to run my program
my aspx.cs
private DataTable TempTable
{
get { return (DataTable)ViewState["TempTable"]; }
set { ViewState["TempTable"] = value; }
}
public void dtTemp()
{
TempTable = new DataTable();
TempTable.Columns.Add("ID_", typeof(string));
TempTable.Columns.Add("Name_", typeof(string));
TempTable.Columns.Add("Phone_", typeof(string));
}
protected void btnAdd_Click(object sender, ImageClickEventArgs e)
{
int rowTotal = Int32.Parse(totalRow.Text);
int i = 0;
panelTest.Visible = true;
dtTemp();
DataRow dr = TempTable.NewRow();
for (; ; )
{
if (i < rowTotal)
{
dr = TempTable.NewRow();
dr["ID_"] = "";
dr["Name_"] = "";
dr["Phone_"] = "";
TempTable.Rows.Add(dr);
grid1.DataSource = TempTable;
grid1.DataBind();
}
else
{
break;
}
}
}
You must try this below increase i++ in your forever loop for(;;)
protected void btnAdd_Click(object sender, ImageClickEventArgs e)
{
int rowTotal = Int32.Parse(totalRow.Text);
int i = 0;
panelTest.Visible = true;
dtTemp();
DataRow dr = TempTable.NewRow();
for (; ; )
{
if (i < rowTotal)
{
dr = TempTable.NewRow();
dr["ID_"] = "";
dr["Name_"] = "";
dr["Phone_"] = "";
TempTable.Rows.Add(dr);
grid1.DataSource = TempTable;
grid1.DataBind();
}
else
{
break;
}
i++;
}
}
my previous code crashes my visual studio and it said i have no enough memory so i changed my code a little and it work.
public DataTable TempTable
{
get; set;
}
public void dtTemp()
{
TempTable = new DataTable();
TempTable.Columns.Add("ID_", typeof(string));
TempTable.Columns.Add("Name_", typeof(string));
TempTable.Columns.Add("Phone_", typeof(string));
}
protected void btnAdd_Click(object sender, ImageClickEventArgs e)
{
int rowTotal = Int32.Parse(txtRow.Text);
dtTemp();
DataRow dr = TempTable.NewRow();
for (int i = 0; i < rowTotal; i++)
{
dr = TempTable.NewRow();
dr["ID_"] = "";
dr["Name_"] = "";
dr["Phone_"] = "";
TempTable.Rows.Add(dr);
}
grid1.DataSource = TempTable;
grid1.DataBind();
}

I can't Add New Row after Deleting Row in Gridview ASP.net

I have a strange problem with my code
I can't add row because NullReferenceException in my gridview after delete a row.
My logic is when Add new row, i have the other function to SetPreviousData.
When I didn't delete a row, my SetPreviousData is don't raise any exception, but when after deleting a row and create new row, my SetPreviousData raise a exception that NullReferenceException.
This is my code for 'AddNewRow()'
private void AddNewRowToGrid()
{
if (ViewState["vsCurrent"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["vsCurrent"];
DataRow drNewRow = dtCurrentTable.NewRow();
drNewRow["SALES_SO_LITEM_ID"] = Convert.ToInt32(dtCurrentTable.Rows.Count.ToString()+"101");
drNewRow["ITEM_NAME"] = string.Empty;
drNewRow["QUANTITY"] = 0;
drNewRow["PRICE"] = 0;
dtCurrentTable.Rows.Add(drNewRow);
ViewState["vsCurrent"] = dtCurrentTable;
}
else
{
ViewState["vsCurrent"] = SetInitialRow();
}
BindDataGrid();
SetPreviousData(); //Set Previous Data on Postbacks
}
and this function for SetPreviousData
public void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["vsCurrent"] != null)
{
DataTable dt = (DataTable)ViewState["vsCurrent"];
if (dt.Rows.Count > 0)
{
int max_rowindex = gvDetailSales.Rows.Count - 1;
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i].RowState != DataRowState.Deleted)
{
Label box1 = (Label)gvDetailSales.Rows[rowIndex].Cells[1].FindControl("lblItemName");
// raise exception because null
Label box2 = (Label)gvDetailSales.Rows[rowIndex].Cells[2].FindControl("lblQuantity");
Label box3 = (Label)gvDetailSales.Rows[rowIndex].Cells[3].FindControl("lblPrice");
box1.Text = dt.Rows[i]["ITEM_NAME"].ToString();
box2.Text = dt.Rows[i]["QUANTITY"].ToString();
box3.Text = dt.Rows[i]["PRICE"].ToString();
rowIndex++;
}
}
}
}
}
How I can handle it ? Thank You
======================EDITED================================================
This is my function for SetInitialRow
public DataTable SetInitialRow()
{
DataTable dtInitial = new DataTable();
DataRow drInitial = null;
dtInitial.Columns.Add(new DataColumn("SALES_SO_LITEM_ID", typeof(string)));
dtInitial.Columns.Add(new DataColumn("ITEM_NAME", typeof(string)));
dtInitial.Columns.Add(new DataColumn("QUANTITY", typeof(int)));
dtInitial.Columns.Add(new DataColumn("PRICE", typeof(float)));
drInitial = dtInitial.NewRow();
drInitial["SALES_SO_LITEM_ID"] = Convert.ToInt32(dtInitial.Rows.Count.ToString() + "101");
drInitial["ITEM_NAME"] = string.Empty;
drInitial["QUANTITY"] = 0;
drInitial["PRICE"] = 0.0;
dtInitial.Rows.Add(drInitial);
return dtInitial;
}
This is my function for BindDataGrid
public void BindDataGrid()
{
gvDetailSales.DataSource = ViewState["vsCurrent"] as DataTable;
gvDetailSales.DataBind();
}

Generating Datatable using GridView

I am having Grid view and in that grid view i am having one button and on selection of that button i need to insert/update record in data table. If in data table if value is there then the qty field will gonna increase by one. Else new row with qty 1 is inserted in the data table. Now the thing is in GridView1_RowCommand i am writing this code. But it is giving me wrong values in data table. My code is written below. Please help me.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "datacommand")
{
DataTable dt = new DataTable();
if (Session["product_id"] != null)
{
dt = (DataTable)Session["product_id"];
}
DataRow dr;
//dt.Rows[0]["qty"] = data;
if (dt.Rows.Count<=0)
{
dt.Columns.Add("product_id", typeof(Int32));
dt.Columns.Add("qty", typeof(int));
dt.Columns.Add("price", typeof(double));
dt.Columns.Add("total", typeof(double));
dr = dt.NewRow();
dr["product_id"] = e.CommandArgument;
dr["qty"] = 1;
dr["price"] = Convert.ToDouble(GridView1.Rows[0].Cells[3].Text);
dr["total"] = Convert.ToInt32(dr["qty"]) * Convert.ToDouble(dr["price"]);
dt.Rows.Add(dr);
dt.AcceptChanges();
Session["product_id"] = dt;
Response.Write("<script type='javacript'> One time</script>");
}
else
{
//dt = Session["product_id"];
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i]["product_id"].ToString() == e.CommandArgument)
{
dr = dt.NewRow();
dt.Rows[i]["qty"] = Convert.ToInt32(dt.Rows[i]["qty"])+ 1;
dt.Rows[i]["total"] = Convert.ToInt32(dt.Rows[i]["qty"]) * Convert.ToDouble(dt.Rows[i]["price"]);
Session["product_id"] = dt;
dt.AcceptChanges();
Response.Write(dt);
}
}
dr = dt.NewRow();
dr["product_id"] = e.CommandArgument;
dr["qty"] = 1;
dr["price"] = Convert.ToDouble(GridView1.Rows[0].Cells[3].Text);
dr["total"] = Convert.ToInt32(dr["qty"]) * Convert.ToDouble(dr["price"]);
dt.Rows.Add(dr);
dt.AcceptChanges();
Session["product_id"] = dt;
}
//GridViewRow row= e.CommandArgument
////DataColumn prodid = new DataColumn("product_id", typeof(System.Int32));
////dt.Columns.Add(prodid);
////DataColumn qty = new DataColumn("qty", typeof(System.Int32));
////dt.Columns.Add(qty);
//int index = Convert.ToInt32(e.CommandArgument);
//GridViewRow row = GridView1.Rows[index];
//AddShopCart(row.Cells[1].Text.ToString());
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "datacommand")
{
DataTable dt = new DataTable();
if (Session["product_id"] != null)
{
dt = (DataTable)Session["product_id"];
}
DataRow dr;
if (dt.Rows.Count<=0)
{
dt.Columns.Add("product_id", typeof(Int32));
dt.Columns.Add("qty", typeof(int));
dt.Columns.Add("price", typeof(double));
dt.Columns.Add("total", typeof(double));
dr = dt.NewRow();
dr["product_id"] = e.CommandArgument;
dr["qty"] = 1;
dr["price"] = Convert.ToDouble(GridView1.Rows[0].Cells[3].Text);
dr["total"] = Convert.ToInt32(dr["qty"]) * Convert.ToDouble(dr["price"]);
dt.Rows.Add(dr);
dt.AcceptChanges();
Session["product_id"] = dt;
Response.Write("<script type='javacript'> One time</script>");
}
else
{
string aa="new";
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i]["product_id"].ToString() == e.CommandArgument)
{
aa="dup";
}
}
if(aa=="dup")
{
for (int j = 0; j < dt.Rows.Count; j++)
{
if (dt.Rows[j]["product_id"].ToString() == e.CommandArgument)
{
// aa="dup";
dt.Rows[j]["qty"]=Convert.ToString( Convert.ToInt32( dt.Rows[j]["qty"])+1);
dt.AcceptChanges();
}
}
Session["product_id"]=dt;
}
else
{
dt.Columns.Add("product_id", typeof(Int32));
dt.Columns.Add("qty", typeof(int));
dt.Columns.Add("price", typeof(double));
dt.Columns.Add("total", typeof(double));
DataRow dr1=dt.NewRow() ;
dr1["product_id"] = e.CommandArgument;
dr1["qty"] = 1;
dr1["price"] = Convert.ToDouble(GridView1.Rows[0].Cells[3].Text);
dr1["total"] = Convert.ToInt32(dr["qty"]) * Convert.ToDouble(dr["price"]);
dt.Rows.Add(dr);
dt.AcceptChanges();
Session["product_id"] = dt;
}
}
}
}
so this is the answer
First create Class for properties,
you can modify this and then use.
public class myclass
{
public int product_id { get; set; }
public int qty { get; set; }
public double price { get; set; }
public double total { get; set; }
}
and then you can add your code inside GridView1_RowCommand event.
private List<myclass> productDetails = new List<myclass>();
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "datacommand")
{
int productId = Convert.ToInt32(e.CommandArgument.ToString());
bool isexist = productDetails.Any(p => p.product_id == productId);
if (isexist)
{
myclass product = productDetails.Where(p => p.product_id == productId).FirstOrDefault();
productDetails.Add(new myclass
{
product_id = product.product_id,
price = product.price,
qty = product.qty + 1,
total = Convert.ToDouble((product.price) * (product.qty + 1))
});
}
else
{
double productPrice = Convert.ToDouble(GridView1.Rows[0].Cells[3].Text);
double productTotal = productPrice * 1;
productDetails.Add(new myclass
{
product_id = Convert.ToInt32(e.CommandArgument.ToString()),
price = productPrice,
qty = 1,
total = productTotal
});
}
}
}

EventHandlers not firing for DropDownList and button

A coworker and I can't figure out why the EventHandlers in the following code aren't getting fired. The function is called twice before the first page loads, and AutoPostBack is set to true. The lnkbtn button and the ddlDose DropDownList are the ones not being fired. It posts back, but it doesn't call the event handler. Here's some code...can anybody see anything inherently wrong?
Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
tblMedOrdering = (Table)Session["tblMedOrdering"];
List<string>medNames = (List<string>)Session["medNamesList"];
populateMeds(medNames);
}
}
PopulateMeds:
protected void populateMeds(List<string> medNames)
{
if (medNames.Count == 0)
{
tblMedOrdering = (Table)Session["tblMedOrdering"];
}
else
{
DataSet ds = new DataSet();
string strConn = Application["dbconn"].ToString();
using (SqlConnection dbconn = new SqlConnection(strConn))
using (SqlCommand medDbcmd = dbconn.CreateCommand())
{
dbconn.Open();
for (int i = 0; i < medNames.Count; i++)
{
DropDownList ddlDose = new DropDownList();
DropDownList ddlSig = new DropDownList();
int flag = 0;
if ((Table)Session["tblMedOrdering"] != null)
{
for (int j = 0; j < tblMedOrdering.Rows.Count; j++)
{
if (tblMedOrdering.Rows[j].Cells[3].Text == medNames[i].ToString())
{
flag = 1;
ddlSig = (DropDownList)tblMedOrdering.Rows[i].Cells[2].FindControl(medNames[i].ToString() + "ddlSig");
if (ddlSig == null)
{
ddlSig.ID = medNames[i].ToString() + "ddlSig";
ListItem liDefaultSig = new ListItem();
liDefaultSig.Value = "0";
liDefaultSig.Text = "Select . . .";
ddlSig.Items.Add(liDefaultSig);
}
break;
}
}
}
if (flag != 1)
{
ListItem liDefault = new ListItem();
liDefault.Value = "0";
liDefault.Text = "Select . . .";
ddlDose.Items.Add(liDefault);
ddlSig.Items.Add(liDefault);
ddlDose.ID = medNames[i].ToString() + "ddlDose";
ddlSig.ID = medNames[i].ToString() + "ddlSig";
ddlDose.AutoPostBack = true;
ddlDose.TextChanged += new EventHandler(ddlDose_SelectedIndexChanged);
medDbcmd.CommandText = "Select distinct medorderid, dose from ordertablemeds where medordername = '" + medNames[i].ToString() + "'";
SqlDataReader dr = medDbcmd.ExecuteReader();
if (dr != null)
{
while (dr.Read())
{
ListItem liDose = new ListItem();
liDose.Value = dr["medorderid"].ToString();
liDose.Text = dr["dose"].ToString();
ddlDose.Items.Add(liDose);
}
dr.Close();
}
TableRow tr = new TableRow();
tr.ID = medNames[i].ToString() + "TableRow";
TableCell tcDose = new TableCell();
TableCell tcSig = new TableCell();
TableCell tcRemove = new TableCell();
TableCell tcMedName = new TableCell();
tcDose.Controls.Add(ddlDose);
tcSig.Controls.Add(ddlSig);
tcMedName.Text = medNames[i].ToString();
tcMedName.ID = medNames[i].ToString() + "medname";
LinkButton lnkbtn = new LinkButton();
lnkbtn.Text = "X";
lnkbtn.ForeColor = System.Drawing.Color.Red;
lnkbtn.ID = medNames[i].ToString() + "_lnkbtn" + tblMedOrdering.Rows.Count;
lnkbtn.Click += new EventHandler(Reset_Click);
tcRemove.Controls.Add(lnkbtn);
tr.Cells.Add(tcRemove);
tr.Cells.Add(tcDose);
tr.Cells.Add(tcSig);
tr.Cells.Add(tcMedName);
tblMedOrdering.Rows.Add(tr);
}
}
tblMedOrdering.DataBind();
dbconn.Close();
}
}
Session["tblMedOrdering"] = tblMedOrdering;
if (medNames.Count == 0)
{
cpeMeds.Collapsed = true;
cpeMeds.ClientState = "True";
}
List<string> medNamesList = new List<string>();
DropDownList ddl = new DropDownList();
for (int k = 0; k < tblMedOrdering.Rows.Count; k++)
{
ddl = (DropDownList)tblMedOrdering.Rows[k].Cells[1].FindControl(tblMedOrdering.Rows[k].Cells[3].Text +"ddlDose");
ddl.SelectedIndexChanged += new EventHandler(ddlDose_SelectedIndexChanged);
medNamesList.Add(tblMedOrdering.Rows[k].Cells[3].Text);
}
Session["medNamesList"] = medNamesList;
}
PopulateMeds is just a function that gets called in the code-behind and is given a list of string names, so it doesn't need args as if it were a control (objects sender, EventArgs e).
Move that logic to OnInit and the event handlers should function properly, assuming that everything else is correct. I would also check to make sure that you don't have validation interfering with the postback.

Copy data from one datagridview to another in c#

for (int i = 0; i < form2.dataGridView1.Rows.Count; i++)
{
if ( form2.dataGridView2.Rows[i].Cells[0].Value != null &&
(bool) form2.dataGridView2.Rows[i].Cells[0].Value == true )
{
form2.dataGridView2.Rows.Add();
for (int j = 1; j < form2.dataGridView1.Columns.Count; j++)
form2.dataGridView2.Rows[i].Cells[j].Value =
form2.dataGridView1.Rows[i].Cells[j].Value;
}
}
the above code is not giving any result. please tell me how to copy the data of one datagridview to another?
Check Copy from datagridview and paste to second datagridview.
Also, you can do as the following:
//Bind datagridview to linq
var gd1 =
( from a in datagridview.Rows.Cast<DataGridViewRow>()
select new {Column1 = a.Cells["Column1"].Value.ToString() }).tolist();
//loop dg1 and save it to datagridview2
foreach(var b in dg1)
{
datagridview2.Rows.Add(b.Column1);
}
Regards
In form1 copy this code
private void Form1_Load(object sender,EventArgs e)
{
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.Columns.Insert(0, new DataGridViewCheckBoxColumn());
show_chkBox();
SqlConnection con = new SqlConnection("server=(local);DataBase=RIMS;User
d=sa;Password=Rootdb");
SqlCommand com = new SqlCommand("Select * from Master_City", con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds, "city");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "city";
}
private void button1_Click_1(object sender, EventArgs e)
{
DataGridViewRow dr = dataGridView1.SelectedRows[0];
dtItems.Columns.Add("city_ID");
dtItems.Columns.Add("city_Name");
dtItems.Columns.Add("status");
dtItems.Columns.Add("date");
if (dataGridView1.Rows.Count > 1)
{
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
if (dataGridView1.Rows[i].Cells[0].Value != null)
{
DataRow row;
row = dtItems.NewRow();
row["city_ID"] = dataGridView1.Rows[i].Cells[1].Value.ToString();
row["city_Name"] = dataGridView1.Rows[i].Cells[2].Value.ToString();
row["status"] = dataGridView1.Rows[i].Cells[3].Value.ToString();
row["date"] = dataGridView1.Rows[i].Cells[4].Value.ToString();
dtItems.Rows.Add(row);
}
}
}
Form2 frm = new Form2(dtItems);
frm.ShowDialog();
}
in form2 copy this code..
public Form2(DataTable dtIt)
{
dtItems = dtIt;
InitializeComponent();
}
private void AddEmptyRows()
{
for (int i = 1; i <= 5; i++)
{
dataGV.Rows.Add();
}
}
private void Form2_Load(object sender, EventArgs e)
{
AddEmptyRows();
for (int i = 0; i < dtItems.Rows.Count; i++)
{
dataGV.Rows[i].Cells[0].Value = dtItems.Rows[i]["city_ID"];
dataGV.Rows[i].Cells[1].Value = dtItems.Rows[i]["city_Name"];
dataGV.Rows[i].Cells[2].Value = dtItems.Rows[i]["status"];
dataGV.Rows[i].Cells[3].Value = dtItems.Rows[i]["date"];
}
dataGV.Enabled = true;
}
Mirror Data From one Data View into Another Data View
If you just want to mirror the data from one DataGridView in another one. For example: DataGridView1 mirror data in DataGridView2.
DataGridView2.DataSource = DataGridView1.DataSource;
Remember this will only mirror the data from on DataGridView in another one.

Categories

Resources