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
});
}
}
}
Related
Use a for loop to generate numbers, 1-100, and add each number to the dataGridView
After I tried with my code, I only showed one line, which is the last 100.
public void aaa(int i) {
DataTable dt = new DataTable();
dt.Columns.Add("host");
DataRow dr = dt.NewRow();
for (int a = 1; a <= i; a++)
{
dr[a] = i;
}
dt.Rows.Add(dr);
this.dataGridView1.DataSource = dt;
}
private void button1_Click(object sender, EventArgs e) {
for (int i = 1; i <= 254; i++)
{
aaa(i);
}
}
your btn_click function. Every loop will initialize or create a new object inside the aaa(i) function
Every time aaa(i) is called in the for loop DataTable dt = new DataTable() will be called
public void aaa(int i)
{
DataTable dt = new DataTable(); ///this will initialize every time, a new data table will be created every loop
dt.Columns.Add("host");
DataRow dr = dt.NewRow();
for (int a = 1; a <= i; a++)
{
dr[a] = i;
}
dt.Rows.Add(dr);
this.dataGridView1.DataSource = dt;
}
}
Might i suggest you pass the 254 int in your aaa(i) function and do the loop inside like
private void button1_Click(object sender, EventArgs e)
{
aaa(254);
}
public void aaa(int i) //value of i = 254
{
DataTable dt = new DataTable();
DataRow dr = dt.NewRow();
for (var s = 0; s <= i; s++ ) {
for (int a = 1; a <= i; a++)
{
dr[a] = i;
}
dt.Rows.Add(dr);
this.dataGridView1.DataSource = dt;
}
}
}
or if the reason for the loop in the button is just for the number limit in the loop inside void aaa then you can simplify it as
public void aaa(int i) //value of i = 254
{
DataTable dt = new DataTable();
DataRow dr = dt.NewRow();
for (int a = 1; a <= i; a++)
{
dr[a] = i;
}
dt.Rows.Add(dr);
this.dataGridView1.DataSource = dt;
}
}
I thought of the available solutions myself.
DataTable dt = new DataTable();
dt.Columns.Add("number");
int i = 10;
int a = 0;
while (a<=i)
{
DataRow dr = dt.NewRow();
a++;
dr[0] = a;
dt.Rows.Add(dr);
}
this.dataGridView1.DataSource = dt;
I always do this like that
ListCollectionView collectionView;
collectionView = new ListCollectionView(*your list of items*);
datagridView1.ItemSource = collectionView;
Implementing like this give you in future open way for sorting, filtering etc. Here is link to ms documentation. where you will find more information about listCollectionView.
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 have to using a datagridview in my project so need to show datagridview column in left side of datagridview like,
column 1 column 2
-------------------------------------------
column 1
column 2
...
`// TODO: This line of code loads data into the 'hRPayDataSet.employee' table. You can move, or remove it, as needed.
this.employeeTableAdapter.Fill(this.hRPayDataSet.employee);
dataGridView1.DataSource =employeeBindingSource;
DataTable table2 = (DataTable)(dataGridView1.DataSource);
dataGridView1.DataSource = null;
DataTable tTable = null;
try { tTable = GenerateTransposedTable(table2); }
catch (Exception ex) { MessageBox.Show(ex.Message); }
dataGridView1.DataSource = tTable;
dataGridView1.RowHeadersVisible = true;
dataGridView1.ColumnHeadersVisible = false;`
please help me....
You can try this: First bind your DataGridView to DataTable
DataTable table = (DataTable)(dataGridView1.DataSource);
DataTable tTable = null;
try
{
tTable = GenerateTransposedTable(table);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
dataGridView1.DataSource = tTable;
dataGridView1.RowHeadersVisible = true;
dataGridView1.ColumnHeadersVisible = false;
GenerateTransposedTable transposes your table:
private DataTable GenerateTransposedTable(DataTable inputTable)
{
DataTable outputTable = new DataTable();
outputTable.Columns.Add(inputTable.Columns[0].ColumnName.ToString());
foreach (DataRow inRow in inputTable.Rows)
{
string newColName = inRow[0].ToString();
outputTable.Columns.Add(newColName);
}
for (int rCount = 0; rCount <= inputTable.Columns.Count - 1; rCount++)
{
DataRow newRow = outputTable.NewRow();
newRow[0] = inputTable.Columns[rCount].ColumnName.ToString();
for (int cCount = 0; cCount <= inputTable.Rows.Count - 1; cCount++)
{
string colValue = inputTable.Rows[cCount][rCount].ToString();
newRow[cCount + 1] = colValue;
}
outputTable.Rows.Add(newRow);
}
return outputTable;
}
Test Code:
private void Form1_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("A");
table.Columns.Add("B");
table.Columns.Add("C");
table.Columns.Add("D");
table.Columns.Add("E");
table.Columns.Add("F");
dataGridView2.DataSource = table;
DataTable table2 = (DataTable)(dataGridView2.DataSource);
DataTable tTable = null;
try
{
tTable = GenerateTransposedTable(table2);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
dataGridView2.DataSource = tTable;
dataGridView2.RowHeadersVisible = true;
dataGridView2.ColumnHeadersVisible = false;
}
UPDATE 2:
Replace Your code with this:
// TODO: This line of code loads data into the 'hRPayDataSet.employee' table. You can move, or remove it, as needed.
this.employeeTableAdapter.Fill(this.hRPayDataSet.employee);
dataGridView1.DataSource = employeeBindingSource;
var bds = (BindingSource)(dataGridView1.DataSource);
HRPayDataSet ds = (HRPayDataSet)bds.DataSource;
DataTable dt = TransposeTable(ds.Tables[0]);
dataGridView1.Columns.Clear();
dataGridView1.DataSource = null;
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dt;
new TransposeTable() method:
private DataTable TransposeTable(DataTable inputTable)
{
DataTable outputTable = new DataTable();
for (int i = 0; i < inputTable.Rows.Count; i++)
{
outputTable.Columns.Add("col" + i);
}
for (int rCount = 0; rCount <= inputTable.Columns.Count - 1; rCount++)
{
DataRow newRow = outputTable.NewRow();
newRow[0] = inputTable.Columns[rCount].ColumnName.ToString();
for (int cCount = 0; cCount <= inputTable.Rows.Count - 2; cCount++)
{
string colValue = inputTable.Rows[cCount][rCount].ToString();
newRow[cCount + 1] = colValue;
}
outputTable.Rows.Add(newRow);
}
return outputTable;
}
i want to keep adding data in current row of grid unless i press clear button to change row but when ever i start adding data in new added row it creates a new row . I want to hold previous rows . any help !!!
public partial class WebForm5 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!(IsPostBack))
{
Session["List"] = null;
ViewState["i"] = ViewState["j"] = 1;
ViewState["state"] = "";
}
}
public static DataTable dt;
public static int i = 1;
protected void txtName_Click(object sender, EventArgs e)
{
Session["List"] = dt;
dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(int)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
if (Convert.ToInt16 (ViewState ["i"]) ==Convert.ToInt16( ViewState["j"]))
{
// here i have to add something
dr = dt.NewRow();
ViewState["state"] = txtName.Text;
dr["RowNumber"] = i;
dr["Column1"] = Convert.ToString(ViewState["state"]) + txtName.Text;
dt.Rows.Add(dr);
}
else if ( Convert .ToInt16 ( ViewState["i"] )!= Convert .ToInt16 ( ViewState["j"]))
{
if (Session["List"] != null)
{
dt = (DataTable)Session["List"];
dr = dt.NewRow();
dr["Column1"] = txtName.Text;
dr["RowNumber"] = i;
ViewState["state"] = txtName.Text;
dt.Rows.Add(dr);
//lst = (List<string>)Session["List"];
//lst.Insert(i,txtAdd.Text);
//i++;
}
ViewState["i"] = ViewState["j"];
}
grdData.DataSource = dt;
grdData.DataBind();
}
protected void btnClr_Click(object sender, EventArgs e)
{
ViewState["j"] = i++;
}
}
public partial class WebForm5 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!(IsPostBack))
{
Session["List"] = null;
ViewState["i"] = ViewState["j"] = 1;
ViewState["state"] = "";
}
}
public static DataTable dt;
public static int i = 1;
protected void txtName_Click(object sender, EventArgs e)
{
Session["List"] = dt;
dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(int)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
if (Session["List"] == null)
{
if (Convert.ToInt16(ViewState["i"]) == Convert.ToInt16(ViewState["j"]))
{
dr = dt.NewRow();
dr["RowNumber"] = i;
dr["Column1"] = Convert.ToString(ViewState["state"]) + txtName.Text;
ViewState["state"] = Convert.ToString(ViewState["state"]) + txtName.Text;
dt.Rows.Add(dr);
}
grdData.DataSource = dt;
grdData.DataBind();
}
if (Session["List"] != null)
{
if ( Convert .ToInt16 ( ViewState["i"] )!= Convert .ToInt16 ( ViewState["j"]))
{
dt = (DataTable)Session["List"];
dr = dt.NewRow();
dr["Column1"] = txtName.Text;
dr["RowNumber"] = i;
dt.Rows.Add(dr);
//lst = (List<string>)Session["List"];
//lst.Insert(i,txtAdd.Text);
//i++;
grdData.DataSource = dt;
grdData.DataBind();
}
else if (Convert.ToInt16(ViewState["i"]) == Convert.ToInt16(ViewState["j"]))
{
dt = (DataTable)Session["List"];
ViewState["state"] = grdData.Rows[((grdData.Rows.Count) - 1)].Cells[1].Text;
string i =Convert.ToString( ViewState["state"]);
int j = dt.Rows.Count;
dt.Rows[(dt.Rows.Count)-1]["Column1"] =Convert.ToString(ViewState["state"])+ txtName.Text;
grdData.DataSource = dt;
grdData.DataBind();
}
ViewState["i"] = ViewState["j"];
}
txtName.Text = "";
}
protected void btnClr_Click(object sender, EventArgs e)
{
ViewState["j"] = i++;
ViewState["state"] = "";
// txtName.Text = grdData.Rows[(grdData.Rows.Count - 1)].Cells[1].Text;
}
protected void btnnew_Click(object sender, EventArgs e)
{
dt.Rows[(grdData.Rows.Count - 1)]["Column1"] = txtName.Text;
grdData.DataSource = dt;
grdData.DataBind();
}
}
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.