Morethan one Gridview one Row Databound? - c#

protected void gvMeatDispatch_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.Parent.Parent.ID == "gvMeatDispatch")
{
DataTable dtpartyname = new DataTable();
objRetailPL.status = 4;
dtpartyname = objRetailBAL.GetType(objRetailPL);
DropDownList ddlpn = (DropDownList)e.Row.FindControl("ddlpartyname");
if (ddlpn != null)
{
ddlpn.DataSource = dtpartyname;
ddlpn.DataTextField = "partyname";
ddlpn.DataValueField = "sno";
ddlpn.DataBind();
ddlpn.Items.Add(new ListItem("--Select--", "0"));
ddlpn.SelectedIndex = ddlpn.Items.Count - 1;
}
}
if (e.Row.Parent.Parent.ID== "gvRetail")
{
DataTable dttypeRT = new DataTable();
dttypeRT = objRetailBAL.getretailtype();
DropDownList ddl = (DropDownList)e.Row.FindControl("ddltype");
if (ddl != null)
{
ddl.DataSource = dttypeRT;
ddl.DataTextField = "type";
ddl.DataValueField = "sno";
ddl.DataBind();
ddl.Items.Add(new ListItem("--Select--", "0"));
ddl.SelectedIndex = ddl.Items.Count - 1;
}
}
}
Here "gvMeatDispatch" and "gvRetail" are two gridviews in row databound..my if condition is satisfied but second "gvRetail" is not executed..please help me

Related

Handle event in dynamically created button in Gridview

I have created dynamic textboxs and dropdownlist in gridview. It is working perfectly. Further I want to fire event in dynamic dropdownlist and do some action.
private ArrayList GetDummyData() {
ArrayList arr = new ArrayList();
arr.Add(new ListItem("Item1", "1"));
arr.Add(new ListItem("Item2", "2"));
arr.Add(new ListItem("Item3", "3"));
arr.Add(new ListItem("Item4", "4"));
arr.Add(new ListItem("Item5", "5"));
return arr;
}
private void FillDropDownList(DropDownList ddl) {
ArrayList arr = GetDummyData();
foreach (ListItem item in arr) {
ddl.Items.Add(item);
}
}
private void SetInitialRow() {
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));//for TextBox value
dt.Columns.Add(new DataColumn("Column2", typeof(string)));//for TextBox value
dt.Columns.Add(new DataColumn("Column3", typeof(string)));//for DropDownList selected item
dt.Columns.Add(new DataColumn("Column4", typeof(string)));//for DropDownList selected item
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dt.Rows.Add(dr);
//Store the DataTable in ViewState for future reference
ViewState["CurrentTable"] = dt;
//Bind the Gridview
Gridview1.DataSource = dt;
Gridview1.DataBind();
//After binding the gridview, we can then extract and fill the DropDownList with Data
DropDownList ddl1 = (DropDownList)Gridview1.Rows[0].Cells[3].FindControl("DropDownList1");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[0].Cells[4].FindControl("DropDownList2");
FillDropDownList(ddl1);
FillDropDownList(ddl2);
}
private void AddNewRowToGrid() {
if (ViewState["CurrentTable"] != null) {
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0) {
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = dtCurrentTable.Rows.Count + 1;
//add new row to DataTable
dtCurrentTable.Rows.Add(drCurrentRow);
//Store the current data to ViewState for future reference
ViewState["CurrentTable"] = dtCurrentTable;
for (int i = 0; i < dtCurrentTable.Rows.Count - 1; i++) {
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("TextBox2");
dtCurrentTable.Rows[i]["Column1"] = box1.Text;
dtCurrentTable.Rows[i]["Column2"] = box2.Text;
//extract the DropDownList Selected Items
DropDownList ddl1 = (DropDownList)Gridview1.Rows[i].Cells[3].FindControl("DropDownList1");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[i].Cells[4].FindControl("DropDownList2");
// Update the DataRow with the DDL Selected Items
dtCurrentTable.Rows[i]["Column3"] = ddl1.SelectedItem.Text;
dtCurrentTable.Rows[i]["Column4"] = ddl2.SelectedItem.Text;
}
//Rebind the Grid with the current data to reflect changes
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else {
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
private void SetPreviousData() {
int rowIndex = 0;
if (ViewState["CurrentTable"] != null) {
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0) {
for (int i = 0; i < dt.Rows.Count; i++) {
TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("TextBox2");
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[3].FindControl("DropDownList1");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[4].FindControl("DropDownList2");
//Fill the DropDownList with Data
FillDropDownList(ddl1);
FillDropDownList(ddl2);
if (i < dt.Rows.Count - 1) {
//Assign the value from DataTable to the TextBox
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
//Set the Previous Selected Items on Each DropDownList on Postbacks
ddl1.ClearSelection();
ddl1.Items.FindByText(dt.Rows[i]["Column3"].ToString()).Selected = true;
ddl2.ClearSelection();
ddl2.Items.FindByText(dt.Rows[i]["Column4"].ToString()).Selected = true;
}
rowIndex++;
}
}
}
}
protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
SetInitialRow();
}
}
protected void ButtonAdd_Click(object sender, EventArgs e) {
AddNewRowToGrid();
}
protected void Gridview1_RowCreated(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.DataRow) {
DataTable dt = (DataTable)ViewState["CurrentTable"];
LinkButton lb = (LinkButton)e.Row.FindControl("LinkButton1");
if (lb != null) {
if (dt.Rows.Count > 1) {
if (e.Row.RowIndex == dt.Rows.Count - 1) {
lb.Visible = false;
}
}
else {
lb.Visible = false;
}
}
}
}
protected void LinkButton1_Click(object sender, EventArgs e) {
LinkButton lb = (LinkButton)sender;
GridViewRow gvRow = (GridViewRow)lb.NamingContainer;
int rowID = gvRow.RowIndex;
if (ViewState["CurrentTable"] != null) {
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 1) {
if (gvRow.RowIndex < dt.Rows.Count - 1) {
//Remove the Selected Row data and reset row number
dt.Rows.Remove(dt.Rows[rowID]);
ResetRowID(dt);
}
}
//Store the current data in ViewState for future reference
ViewState["CurrentTable"] = dt;
//Re bind the GridView for the updated data
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
//Set Previous Data on Postbacks
SetPreviousData();
}
private void ResetRowID(DataTable dt) {
int rowNumber = 1;
if (dt.Rows.Count > 0) {
foreach (DataRow row in dt.Rows) {
row[0] = rowNumber;
rowNumber++;
}
}
}
Might be a duplicate of question:
how to add an OnClick event on DropDownList's ListItem that is added dynamically?
Please check the answer given there.
DropDownList changesList = new DropDownList();
ListItem item;
item = new ListItem();
item.Text = "go to google.com";
item.Value = "http://www.google.com";
changesList.Items.Add(item);
changesList.Attributes.Add("onChange", "location.href = this.options[this.selectedIndex].value;");
Also have you tried adding a handler to the event SelectedIndexChanged dynamically when adding the new row to the grid?

My Cart Label Value is not increasing in masterpage?

MasterPage Code:
public Label OnlbCartCountMasterPage {
get { return this.chartlabel; }
}
Index.aspx Code
String cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
string cartQuantity;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadList();
}
if (Session["addtocart"] != null)
{
DataTable dt = new DataTable();
cartQuantity = Convert.ToString(dt.Rows.Count);
}
else
{
cartQuantity = "0";
}
Master.OnlbCartCountMasterPage.Text = cartQuantity;
}
Add2cart Method:
private void add2cart(int id,string lblname,int lblPrice, int lbltotal, int quantitylist, string image)
{
if (Session["addtocart"] != null)
{
DataTable dt = (DataTable)Session["addtocart"];
var dataRow = dt.AsEnumerable().Where(x => x.Field<int>("ID") == id);
if (dataRow.Count() == 0)
{
//lblErrorMessage.Text = "";
DataRow dr = dt.NewRow();
dr["ID"] = id;
dr["Item"] = lblname;
dr["Price"] = lblPrice;
dr["quantity"] = quantitylist;
dr["total"] = lbltotal;
dr["image"] = image;
dt.Rows.Add(dr);
Session["addtocart"] = dt;
cartQuantity= dt.Rows.Count.ToString();
Master.OnlbCartCountMasterPage.Text = cartQuantity;
}
else
{
//lblErrorMessage.Text = "Item Already Added!";
}
}
else
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Item", typeof(string));
dt.Columns.Add("Price", typeof(int));
dt.Columns.Add("quantity", typeof(int));
dt.Columns.Add("total", typeof(int));
dt.Columns.Add("image", typeof(string));
DataRow dr = dt.NewRow();
dr["ID"] = id;
dr["Item"] = lblname;
dr["Price"] = lblPrice;
dr["quantity"] = quantitylist;
dr["total"] = lbltotal;
dr["image"] = image;
dt.Rows.Add(dr);
Session["addtocart"] = dt;
cartQuantity=Convert.ToString(dt.Rows.Count);
}
Master.OnlbCartCountMasterPage.Text = cartQuantity;
}
Button Code
protected void btnAddtoCart_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
ListViewItem item = (ListViewItem)btn.NamingContainer;
HiddenField hfid = item.FindControl("hfId") as HiddenField;
Label lblitem= item.FindControl("item") as Label;
Label lblPrice = item.FindControl("lblPrice") as Label;
DropDownList lblQuantity = item.FindControl("qtydrpdwn") as DropDownList;
Label lblTotal = item.FindControl("Total") as Label;
HiddenField hfimg = item.FindControl("imgpath") as HiddenField;
add2cart(Convert.ToInt32(hfid.Value),lblitem.Text, Convert.ToInt32(lblPrice.Text), Convert.ToInt32(lblTotal.Text), Convert.ToInt32(lblQuantity.Text),hfimg.Value);
btn.Enabled = false;
//Response.Redirect("index.aspx");
}
The problem is occuring in pageload i think? because session is not recognizing the value coming from add2cart method. it is showing the value in the session of add to cart but not in page load. i cant finding out the problem in the code?
And when i click the button to add to cart. the value remains same 0 not increasing at all?
Try this. I outsourced the update routine in a seperate method which is called each time the button is pressed.
String cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
string cartQuantity;
// this will be executed when the page is loaded at the beginning or when refreshed
protected void Page_Load(object sender, EventArgs e)
{
// I don't know what this does, if you also need it for the update
// then put it into the updateQuantity method
if (!IsPostBack)
{
LoadList();
}
// update quantity
updateQuantity();
}
// method to update the quantity
private void updateQuantity()
{
if (Session["addtocart"] != null)
{
DataTable dt = new DataTable();
cartQuantity = Convert.ToString(dt.Rows.Count);
}
else
{
cartQuantity = "0";
}
Master.OnlbCartCountMasterPage.Text = cartQuantity;
}
protected void btnAddtoCart_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
ListViewItem item = (ListViewItem)btn.NamingContainer;
HiddenField hfid = item.FindControl("hfId") as HiddenField;
Label lblitem= item.FindControl("item") as Label;
Label lblPrice = item.FindControl("lblPrice") as Label;
DropDownList lblQuantity = item.FindControl("qtydrpdwn") as DropDownList;
Label lblTotal = item.FindControl("Total") as Label;
HiddenField hfimg = item.FindControl("imgpath") as HiddenField;
add2cart(Convert.ToInt32(hfid.Value),lblitem.Text, Convert.ToInt32(lblPrice.Text), Convert.ToInt32(lblTotal.Text), Convert.ToInt32(lblQuantity.Text),hfimg.Value);
btn.Enabled = false;
//call update method
updateQuantity();
}

the selectedindex and selectedvalue attributes are mutually exclusive exception?

protected void ddlbranchdate_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
DataTable dtgetvalues = new DataTable();
//objRetailPL.date = Convert.ToDateTime(hdndate.Value);
objRetailPL.branchdate = ddlbranchdate.SelectedItem.ToString();
dtgetvalues = objRetailBAL.getbradisdate(objRetailPL);
foreach(GridViewRow row in gvMeatDispatch.Rows)
{
DataTable dtpr = new DataTable();
DropDownList ddl1 = (DropDownList)row.FindControl("ddlpartyname");
objRetailPL.branch = dtgetvalues.Rows[0]["branch"].ToString();
dtpr = objRetailBAL.getbran(objRetailPL);
ddl1.DataSource = dtpr;
ddl1.DataTextField = "partyname";
ddl1.DataValueField = "sno";
ddl1.DataBind();
ddl1.Items.Add(new ListItem("--Select--", "0"));
ddl1.SelectedIndex = ddl1.Items.Count - 1;
}
}
}
why i am getting this exception?..
i am using Dynamic Gridview and adding Rows Dynamically with the help of Button Control..
Outside i am declare another dropdown list ..if user selected some value from this Dropdownlist
then automatically bind the values to Dynamic Gridview ,Dropdown list values..
This is my Setprevious Data in Dynamic control Method..Here i called Dropdownlist selectedindexchanged event ..like..
private void SetPreviousData()
{
try
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
DropDownList ddlpname = (DropDownList)gvMeatDispatch.Rows[rowIndex].Cells[1].FindControl("ddlpartyname");
DropDownList ddlbt = (DropDownList)gvMeatDispatch.Rows[rowIndex].Cells[2].FindControl("ddlbirdtype");
TextBox txttotwt = (TextBox)gvMeatDispatch.Rows[rowIndex].Cells[3].FindControl("txttotwt");
TextBox txttransbirds1 = (TextBox)gvMeatDispatch.Rows[rowIndex].Cells[4].FindControl("txtrateforkg");
TextBox txtmort1 = (TextBox)gvMeatDispatch.Rows[rowIndex].Cells[5].FindControl("txtdcno");
// Dropdownlist selectedIndex Changed event
ddlbranchdate_SelectedIndexChanged(null, null);
ddlpname.SelectedValue = dt.Rows[i]["Col1"].ToString();
ddlbt.SelectedValue = dt.Rows[i]["Col2"].ToString();
txttotwt.Text = dt.Rows[i]["col3"].ToString();
txttransbirds1.Text = dt.Rows[i]["Col4"].ToString();
txtmort1.Text = dt.Rows[i]["Col5"].ToString();
rowIndex++;
}
}
}
}

How to enable CheckBoxField in GridView dynamically?

I generate CheckBoxField in GridView dynamically. but in output the CheckBox is disabled.
How to enable CheckBox dynamically.
I know if add a TemplateField in GridView markup my problem is solved but i won't add TemplateField in GridView
ASPX:
<asp:GridView ID="GridView2" runat="server">
</asp:GridView>
Code behind:
DataTable dTable = new DataTable();
dTable.Columns.Add("c1", typeof(bool));
DataRow r = dTable.NewRow();
r[0] = false;
dTable.Rows.Add(r);
r = dTable.NewRow();
r[0] = true;
dTable.Rows.Add(r);
CheckBoxField chkField = new CheckBoxField();
chkField.DataField = "c1";
chkField.HeaderText = "CheckBox";
chkField.ReadOnly = false;
GridView2.Columns.Add(chkField);
GridView2.DataSource = dTable;
GridView2.DataBind();
I put code in the RowDataBound event to enable the checkbox:
protected void Page_Load(object sender, EventArgs e)
{
this.GridView2.RowDataBound += GridView2_RowDataBound;
BindGrid();
}
void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.Cells[0].GetType() == typeof(System.Web.UI.WebControls.DataControlFieldCell))
{
TableCell tc = e.Row.Cells[0];
if (tc.Controls.Count > 0)
{
CheckBox cb = (CheckBox)tc.Controls[0];
if (!(cb == null))
{
cb.Enabled = true;
}
}
}
}
private void BindGrid()
{
DataTable dTable = new DataTable();
dTable.Columns.Add("c1", typeof(bool));
DataRow r = dTable.NewRow();
r[0] = false;
dTable.Rows.Add(r);
r = dTable.NewRow();
r[0] = true;
dTable.Rows.Add(r);
//CheckBoxField chkField = new CheckBoxField();
//chkField.DataField = "c1";
//chkField.HeaderText = "CheckBox";
//chkField.ReadOnly = false;
//GridView1.Columns.Add(chkField);
GridView2.DataSource = dTable;
GridView2.DataBind();
}
}
Optimize Decker97 answer:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
DataTable dTable = new DataTable();
dTable.Columns.Add("c1", typeof(bool));
DataRow r = dTable.NewRow();
r[0] = false;
dTable.Rows.Add(r);
r = dTable.NewRow();
r[0] = true;
dTable.Rows.Add(r);
GridView2.DataSource = dTable;
GridView2.DataBind();
}
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox cb = (CheckBox)e.Row.Cells[0].Controls[0];
cb.Enabled = true;
}
}

c# Counter requires 2 button clicks to update

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.

Categories

Resources