Setting Rowspan for Dynamic Rows in asp.net Table Control - c#

I've created an asp.net table and added rows to the table dynamically that is using Backend ( C# ) .
The First Column of the Rows should have Rowspan .
The rows are being added very fine and the Rowspan is also added fine but when the Postback occurs , The Rowspans gets changes automatically .
Can any one please help me to solve this problem :(
This is when the page loads First Time:
This is when PostBack Occured First Time :
This is when Postback Occured Second Time :
Thanks in advance
Here is my complete code :
.aspx Code
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style>
.tbl {
border:1px solid #000000;
}
.tbl td,th {
border:1px solid #000000;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Table runat="server" ID="tbl_fund" CssClass="tbl"></asp:Table>
<asp:Button runat="server" Text="Do Post Back" />
</div>
</form>
</body>
</html>
C# Code :
protected void Page_Load(object sender, EventArgs e)
{
PrintFundChanges();
}
public void PrintFundChanges()
{
//***************************Header Started*****************************
TableRow tr_head = new TableRow();
TableHeaderCell th1 = new TableHeaderCell();
th1.Text = "CNIC";
TableHeaderCell th2 = new TableHeaderCell();
th2.Text = "Field Name";
TableHeaderCell th3 = new TableHeaderCell();
th3.Text = "Updated Value";
TableHeaderCell th4 = new TableHeaderCell();
th4.Text = "Current Value";
TableHeaderCell th5 = new TableHeaderCell();
CheckBox chk_head = new CheckBox();
chk_head.ID = "chk_fund";
chk_head.CheckedChanged += new EventHandler(Chk_Fund_CheckedChanged);
chk_head.Text = "Approve / Disapprove";
chk_head.AutoPostBack = true;
th5.Controls.Add(chk_head);
TableHeaderCell th6 = new TableHeaderCell();
th6.Text = "Table Name";
th6.Style.Add("display", "none");
TableHeaderCell th7 = new TableHeaderCell();
th7.Text = "Column Name";
th7.Style.Add("display", "none");
TableHeaderCell th8 = new TableHeaderCell();
th8.Text = "pk_code";
th8.Style.Add("display", "none");
TableHeaderCell th9 = new TableHeaderCell();
th9.Text = "pk2_code";
th9.Style.Add("display", "none");
TableHeaderCell th10 = new TableHeaderCell();
th10.Text = "action_type";
th10.Style.Add("display", "none");
th1.Style.Add("width", "20%");
th2.Style.Add("width", "20%");
th3.Style.Add("width", "20%");
th4.Style.Add("width", "20%");
tr_head.Cells.Add(th1);
tr_head.Cells.Add(th2);
tr_head.Cells.Add(th3);
tr_head.Cells.Add(th4);
tr_head.Cells.Add(th5);
tr_head.Cells.Add(th6);
tr_head.Cells.Add(th7);
tr_head.Cells.Add(th8);
tr_head.Cells.Add(th9);
tr_head.Cells.Add(th10);
tbl_fund.Rows.Add(tr_head);
//****************************Header Ended*******************************
//****************************Print Updated Data Started*************************
//Getting distinct primary key data
//DataTable dt_DistinctPk = dt_FundUpdatedFields.DefaultView.ToTable(true, "pk_code");
DataTable dt_DistinctPk = new DataTable();
dt_DistinctPk.Columns.Add(new DataColumn("pk_code", typeof(string)));
DataRow dr = dt_DistinctPk.NewRow();
dr["pk_code"] = "123";
dt_DistinctPk.Rows.Add(dr);
dr = dt_DistinctPk.NewRow();
dr["pk_code"] = "456";
dt_DistinctPk.Rows.Add(dr);
for (int i = 0; i < dt_DistinctPk.Rows.Count; i++)
{
TableCell td_pk = new TableCell();
td_pk.Text = "<b style='font-size:13px !important;'>" + dt_DistinctPk.Rows[i]["pk_code"].ToString() + "</b>";
//int numberOfRecords = dt_FundUpdatedFields.Select("pk_code = " + dt_DistinctPk.Rows[i]["pk_code"].ToString()).Length;
int numberOfRecords =5;
td_pk.RowSpan = numberOfRecords;
bool IsAddAtOnce = true;
for (int j = 0; j < 5; j++)
{
string field_name_lable = "Column name here";
TableRow tr = new TableRow();
TableCell td1 = new TableCell();
td1.Text = field_name_lable;
TableCell td2 = new TableCell();
TableCell td3 = new TableCell();
td2.Text = "New Value here";
td3.Text = "Old Value here";
TableCell td4 = new TableCell();
CheckBox chk = new CheckBox();
chk.ID = "chk_" +j;
//td4.Controls.Add(chk);
TableCell td5 = new TableCell();
td5.Text = "tbl_name";
td5.Style.Add("display","none");
TableCell td6 = new TableCell();
td6.Text = "field_name";
td6.Style.Add("display", "none");
TableCell td7 = new TableCell();
td7.Text = j.ToString();
td7.Style.Add("display", "none");
TableCell td8 = new TableCell();
td8.Text = j.ToString();
td8.Style.Add("display", "none");
TableCell td9 = new TableCell();
td9.Text = "1";
td9.Style.Add("display", "none");
if (IsAddAtOnce)
{
tr.Cells.Add(td_pk);
IsAddAtOnce = false;
}
tr.Cells.Add(td1);
tr.Cells.Add(td2);
tr.Cells.Add(td3);
tr.Cells.Add(td4);
tr.Cells.Add(td5);
tr.Cells.Add(td6);
tr.Cells.Add(td7);
tr.Cells.Add(td8);
tr.Cells.Add(td9);
tbl_fund.Rows.Add(tr);
if (j ==5 - 1)//Last Termination of Loop
{
//Printing Attachments
td_pk.RowSpan = td_pk.RowSpan + 1;
td1 = new TableCell();
td1.Text = "CNIC Attachment";
td2 = new TableCell();
Image img_new = new Image();
// img_new.ImageUrl = "ImgHandler.ashx?typ=Newfund&emp=" + Requestor + "&pk=" + dt_FundUpdatedAttachments.Rows[k]["pk_code"].ToString();
td2.Controls.Add(img_new);
td3 = new TableCell();
Image img_old = new Image();
//img_old.ImageUrl = "ImgHandler.ashx?typ=Currfund&emp=" + Requestor + "&pk=" + dt_FundUpdatedAttachments.Rows[k]["pk_code"].ToString();
td3.Controls.Add(img_old);
td4 = new TableCell();
chk = new CheckBox();
//chk.ID = "chk_" + dt_FundUpdatedAttachments.Rows[k]["tbl_name"].ToString().ToUpper() + "_" + dt_FundUpdatedAttachments.Rows[k]["field_name"].ToString().ToUpper() + "_" + dt_FundUpdatedAttachments.Rows[k]["pk_code"].ToString().ToUpper() + "_";
td4.Controls.Add(chk);
td5 = new TableCell();
td5.Text = "tbl_name";
td5.Style.Add("display", "none");
td6 = new TableCell();
td6.Text ="field_name";
td6.Style.Add("display", "none");
td7 = new TableCell();
td7.Text = j.ToString();
td7.Style.Add("display", "none");
td8 = new TableCell();
td8.Text = "";
td8.Style.Add("display", "none");
td9 = new TableCell();
td9.Text = "1";
td9.Style.Add("display", "none");
tr = new TableRow();
tr.Cells.Add(td1);
tr.Cells.Add(td2);
tr.Cells.Add(td3);
tr.Cells.Add(td4);
tr.Cells.Add(td5);
tr.Cells.Add(td6);
tr.Cells.Add(td7);
tr.Cells.Add(td8);//pk2_code
tr.Cells.Add(td9);//action_type
tbl_fund.Rows.Add(tr);
}
}
}
////****************************Print New Data Ended***************************
TableRow tr_blank = new TableRow();
TableCell td_blank = new TableCell();
td_blank.Text = "Deleted Data";
td_blank.Style.Add("font-weight", "bold !important");
td_blank.Style.Add("font-size", " 16px !important");
td_blank.Style.Add("background-color", "#e3e3e3 !important");
td_blank.ColumnSpan = 10;
tr_blank.Cells.Add(td_blank);
tbl_fund.Rows.Add(tr_blank);
////****************************Print Deleted Data Started***************************
//****************************Print Deleted Data Ended***************************
}
protected void Chk_Fund_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
bool IsChecked = chk.Checked;
for (int i = 1; i < tbl_fund.Rows.Count; i++)
{
string pk_code = "";
string tbl_name = "";
string col_name = "";
string pk2_code = "";
int CellsCount = tbl_fund.Rows[i].Cells.Count;
/*In this table rowspan is used for printing cnic number,
so the row who has rowspan will have cnic column in first termination ,
while in second termination the cell count will decrease because the
row before the current row will having the rowspan.
*/
if (CellsCount == 10)
{
tbl_name = tbl_fund.Rows[i].Cells[5].Text;
col_name = tbl_fund.Rows[i].Cells[6].Text;
pk_code = tbl_fund.Rows[i].Cells[7].Text;
pk2_code = tbl_fund.Rows[i].Cells[8].Text;
}
else if (CellsCount == 9)
{
tbl_name = tbl_fund.Rows[i].Cells[4].Text;
col_name = tbl_fund.Rows[i].Cells[5].Text;
pk_code = tbl_fund.Rows[i].Cells[6].Text;
pk2_code = tbl_fund.Rows[i].Cells[7].Text;
}
if (tbl_name != "")//if it is not a blank/header row
{
CheckBox ck = new CheckBox();
string chk_id = "chk_" + tbl_name + "_" + col_name + "_" + pk_code + "_" + pk2_code;
ck = (CheckBox)tbl_fund.Rows[i].Cells[4].FindControl(chk_id);//chk_tblname_colname_pk
ck.Checked = IsChecked;
}
}
}

just change the this line from
td_pk.RowSpan = td_pk.RowSpan + 1;
to
td_pk.RowSpan = numberOfRecords + 1;

Related

Find dynamically generated text on button click

I'm using asp.net C# in my project we have dynamically generated textbox inside panel I want to get textbox value,so I'm using the foreach loop for getting the Textbox but I'm not getting the textbox
Here I generate the control
Table table = new Table();
table.ID = "table1";
table.Width = new Unit("100%");
table.BorderWidth = new Unit("1px");
table.CssClass = "tbl";
string Query = "SELECT * FROM XXCUS.MASTER_VERIFICATION";
OracleDataAdapter da = new OracleDataAdapter(Query, obj_Conn);
DataTable dt = new DataTable();
da.Fill(dt);
var Count = dt.Rows.Count;
if (Count > 0)
{
TableHeaderCell cellheader = new TableHeaderCell();
Label lblHeader = new Label();
lblHeader.Text = "Select";
Label lblDesc = new Label();
TableHeaderRow thr = new TableHeaderRow();
TableHeaderCell thc = new TableHeaderCell();
TableHeaderCell thcode = new TableHeaderCell();
TableHeaderCell thcReason = new TableHeaderCell();
thc.Text = "Select";
thcode.Text = "Description";
thcReason.Text = "Reason";
thr.Cells.Add(thc);
thr.Cells.Add(thcode);
//thr.CssClass = "pdlbl";
thc.Width = new Unit("5px");
thcode.Width = new Unit("75%");
thcode.CssClass = "thcode";
thcReason.Width = new Unit("20%");
thcReason.CssClass = "thcReason";
thr.Cells.Add(thcReason);
table.Rows.Add(thr);
for (int i = 0; i < Count; i++)
{
TableRow row = new TableRow();
TableCell cellchk = new TableCell();
TableCell celltxt = new TableCell();
TableCell celldesc = new TableCell();
TextBox txt = new TextBox();
CheckBox chk = new CheckBox();
txt.ID = "txt" + i.ToString();
txt.MaxLength = 250;
//txt.Width = new Unit("84%");
//txt.CssClass = "txtCl";
chk.ID = "chk" + i.ToString();
txt.TextMode = TextBoxMode.MultiLine;
cellchk.ID = "cellchk" + i.ToString();
celltxt.ID = "celltxt" + i.ToString();
cellchk.Controls.Add(chk);
//chk.Attributes.Add("onClick", "alert('" + chk.ID + "')");
Label lblDescription = new Label();
lblDescription.Text = dt.Rows[i]["DESCRIPTION"].ToString();
celldesc.Controls.Add(lblDescription);
cellheader.Controls.Add(lblHeader);
cellchk.Width = new Unit("5%");
//cellchk.CssClass = "pd";
celldesc.Width = new Unit("75%");
//celldesc.CssClass = "pdlbl";
celltxt.Width = new Unit("20%");
celltxt.Controls.Add(txt);
row.Cells.Add(cellchk);
row.Cells.Add(celldesc);
row.Cells.Add(celltxt);
table.Rows.Add(row);
}
dvGenerateCntrl.Controls.Add(table);
}
and I'm using the panel for add the control
<asp:Panel ID="dvGenerateCntrl" runat="server">
</asp:Panel>
I don't see any issues with your above code so maybe the issue is how you adding the textbox control to dvGenerateCntrol.
Can you show this code as well.
Here is some example code of adding a control to a cell within a table and then finding then iterating through the rows and cells to find the textbox.
Table t = new Table();
TableRow tr = new TableRow();
TableCell tc = new TableCell();
System.Web.UI.WebControls.TextBox tb = new System.Web.UI.WebControls.TextBox() { Text = "Testing" };
tc.Controls.Add(tb); //Add Textbox to TableCell Control Collection
tr.Cells.Add(tc); // Add TableCell to TableRow
t.Rows.Add(tr); //Add TableRow to Table
System.Web.UI.WebControls.Panel panel = new System.Web.UI.WebControls.Panel(); //This is your panel
panel.Controls.Add(t); // Add Table to Panel
Table tbl = panel.Controls.OfType<Table>().FirstOrDefault(); //Now to find the TextBox in the Table, in the Row, in the cell
foreach (TableRow row in tbl.Rows) //Loop through each TableRow
{
foreach (TableCell cell in row.Cells) //Loop through each TableCell
{
IEnumerable<System.Web.UI.WebControls.TextBox> txtBoxes = cell.Controls.OfType<System.Web.UI.WebControls.TextBox>(); //Search TableCell.Controls Collection for all TextBoxes
}
}

Holding dynamic Controls on postback not working

I get this error and do not find the problem:
Object reference not set to an instance of an object.
My Code:
Page Init:
else if (Request.QueryString["CompanyID"] != null)
{
pnlComp.Visible = true;
if (Convert.ToString(ViewState["Generated"]) != "true")
{
createCompSite();
ViewState["Generated"] = "true";
}
}
Page Load:
Verification.Check();
if (!IsPostBack)
{
sFilter= null;
FillGridviewAndValues();
}
if (Convert.ToString(ViewState["Generated"]) == "true")
createCompSite();
Function:
TableHeaderRow tHRow = new TableHeaderRow();
TableHeaderCell tHeader = new TableHeaderCell();
tHeader.Text = dr.Field<string>("Loc");
tHRow.Cells.Add(tHeader);
tblCompLoc1.Rows.Add(tHRow);
DataTable dtCat = new DataTable();
dtCat = SQLCon.SQLCommand_DokuTool("SELECT CL.ID, C.CatName FROM TBL_Ref_CatLoc AS CL, TBL_Category AS C WHERE C.CatID = CL.CatID AND CL.LocID = '" + dr.Field<Guid>("ID").ToString() + "' AND CL.Approved='True' ORDER BY CatName ASC");
foreach (DataRow dr2 in dtCat.Rows)
{
//Working as plain Text
//TableRow tRow = new TableRow();
//TableCell tCell = new TableCell();
//tCell.Text = dr2.Field<string>("CatName");
//tRow.Cells.Add(tCell);
//tblCompLoc1.Rows.Add(tRow);
//Not working as Hyperlink or Btn
TableRow tRow = new TableRow();
TableCell tCell = new TableCell();
HyperLink hl = new HyperLink();
hl.EnableViewState=true;
hl.Text = dr2.Field<string>("CatName");
string gLocID = SQLCon.SQLCommand_User("SELECT ID FROM TBL_Location WHERE fCompanyID = '"+sRequest+"' AND City + ', ' + Street1 ='"+tHeader.Text+"'").Rows[0].Field<Guid>("ID").ToString();
string gCatID = SQLCon.SQLCommand_DokuTool("SELECT CatID FROM TBL_Category WHERE CatName='"+hl.Text+"'").Rows[0].Field<Guid>("CatID").ToString();
string sRequestedCat = SQLCon.SQLCommand_DokuTool("SELECT ID FROM TBL_Ref_CatLoc WHERE LocID = '"+gLocID+"' AND CatID='"+gCatID+"'").Rows[0].Field<Guid>("ID").ToString();
hl.NavigateUrl="~/Default?ID="+sRequestedCat;
tCell.Controls.Add(hl);
tRow.Controls.Add(tCell);
tblCompLoc1.Rows.Add(tRow);
}
I want to create a Table which is filled from DataBase and can look different on each site and every Table Cell should have a different Link where it leads the user. The table creation starts on page init.

Saving text of dynamic textboxes and labels on dynamically created linkbutton click event

I am developing a shopping cart kind of thing. For that, on selecting products they get added to a temporary table, and so on. Then a popup window opens which loads dynamic labels, text-boxes and linkbutton based on the number of rows in the temporary table in the page load event. I want to allow users to change the textbox field which is the quantity of the product, and immediately update in the database using the dynamically created linkbutton.
I tried using Viewstate but I am unable to do it according to my need. Also , I read many other articles and posts on stack-overflow and other blogs too, but could not work out.
Here is my code:-
protected void Page_Load(object sender, EventArgs e)
{
Session["date"] = DateTime.Now.ToShortDateString();
productListing();
LabelCost.Text = total.ToString("F");
}
public void productListing()
{
//...................................Product Listing...............................
con2.Close();
con2.Open();
SqlDataAdapter adp12 = new SqlDataAdapter("select * from db_temporary_cart where(IP_address='" + Request.QueryString["ip"].ToString() + "' AND date='" + Session["date"] + "') ORDER BY counter DESC", con2);
DataSet ds12 = new DataSet();
adp12.Fill(ds12, "db_temporary_cart");
int count12 = ds12.Tables[0].Rows.Count;
if (count12 > 0)
{
totalProductRpwsincategory = count12;
//................storing products id of the category.....................
arr_product_id = new string[count12];
arr_product_name = new string[count12];
arr_product_qty = new int[count12];
arr_product_price = new double[count12];
arr_product_subtotal = new double[count12];
for (int i = 0; i < count12; i++)
{
arr_product_id[i] = ds12.Tables[0].Rows[i]["product_id"].ToString();
arr_product_qty[i] = Convert.ToInt32(ds12.Tables[0].Rows[i]["quantity"]);
}
con2.Close();
for (int i = 0; i < arr_product_id.Length; i++)
{
con2.Close();
con3.Close();
con3.Open();
SqlDataAdapter adp123 = new SqlDataAdapter("select * from db_product_management where(product_id='" + arr_product_id[i].ToString() + "' AND product_stock_availability='" + "In-Stock" + "')", con3);
DataSet ds123 = new DataSet();
adp123.Fill(ds123, "db_product_management");
int count123 = ds123.Tables[0].Rows.Count;
if (count123 > 0)
{
arr_product_name[i] = ds123.Tables[0].Rows[0]["product_name"].ToString();
arr_product_price[i] = Convert.ToDouble(ds123.Tables[0].Rows[0]["product_price"]);
arr_product_subtotal[i] = Convert.ToDouble((arr_product_price[i])*(arr_product_qty[i]));
total = total + arr_product_subtotal[i];
con3.Close();
}
con3.Close();
}
//................storing products id of the category.....................
Table table = new Table();
var collection = new List<string>();
for (int i = 0; i < totalProductRpwsincategory; i++)
{
TableRow row = new TableRow();
row.CssClass = "dynamicMain";
System.Web.UI.HtmlControls.HtmlGenericControl createDivMain = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
createDivMain.Attributes["class"] = "dynamicMain";
ImageButton imgLink = new ImageButton();
imgLink.Attributes.Add("width", "150px");
imgLink.Attributes.Add("height", "104px");
imgLink.Attributes["class"] = "dynamicIMG";
imgLink.CommandArgument = arr_product_id[i];
imgLink.CommandName = arr_product_name[i];
imgLink.Command += new CommandEventHandler(this.OnDynamicLinkButtonClick);
System.Web.UI.HtmlControls.HtmlGenericControl createDiv1 = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
createDiv1.Attributes["class"] = "sub-category-productsDisplayBlockText1_Dynamic";
Label linkProduct = new Label();
linkProduct.Text = arr_product_name[i];
LinkButton linkSaveQty = new LinkButton();
linkSaveQty.Text = arr_product_name[i];
linkSaveQty.Font.Underline = false;
linkSaveQty.ID = i.ToString();
linkSaveQty.Text = "Save";
linkSaveQty.CommandArgument = arr_product_id[i];
linkSaveQty.Attributes["class"] = "dynamicSaveQty";
linkSaveQty.Command += new CommandEventHandler(this.OnDynamicLinkButtonClickSave);
//linkSaveQty.CausesValidation = false;
System.Web.UI.HtmlControls.HtmlGenericControl createDivTb = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
TextBox tb = new TextBox();
//tb.ID = arr_product_id[i] + Guid.NewGuid().ToString("N");
tb.ID = arr_product_id[i];
tb.Text = arr_product_qty[i].ToString();
tb.Attributes["class"] = "dynamicTB";
Label linkQty = new Label();
linkQty.Text = "Quantity";
linkQty.Attributes["class"] = "dynamicQty";
collection.Add(tb.ID);
System.Web.UI.HtmlControls.HtmlGenericControl createDiv3 = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
createDiv3.Attributes["class"] = "sub-category-productsDisplayBlockText1_Dynamic_Price";
Label linkPrice = new Label();
linkPrice.Text = arr_product_price[i].ToString();
System.Web.UI.HtmlControls.HtmlGenericControl createDiv2 = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
createDiv2.Attributes["class"] = "sub-category-productsDisplayBlockText1_Dynamic_SubTotal";
Label linkSubTotal = new Label();
linkSubTotal.Text = arr_product_subtotal[i].ToString();
ImageButton imgLinkDelete = new ImageButton();
imgLinkDelete.Attributes.Add("width", "25px");
imgLinkDelete.Attributes.Add("height", "25px");
imgLinkDelete.CommandArgument = arr_product_id[i];
imgLinkDelete.Command += new CommandEventHandler(this.OnDynamicLinkButtonClickDelete);
for (int j = 0; j < 1; j++)
{
imgLink.ImageUrl = "NImageMainProductImage.ashx?PhotoId=" + arr_product_id[i];
TableCell cell = new TableCell();
cell.Controls.Add(imgLink);
row.Cells.Add(cell);
cell.VerticalAlign = VerticalAlign.Top;
}
for (int j = 1; j < 2; j++)
{
TableCell cell = new TableCell();
cell.Controls.Add(createDiv1);
createDiv1.Controls.Add(linkProduct);
row.Cells.Add(cell);
cell.VerticalAlign = VerticalAlign.Top;
}
for (int j = 2; j < 3; j++)
{
TableCell cell = new TableCell();
cell.Controls.Add(linkQty);
cell.Controls.Add(new LiteralControl("<br>"));
cell.Controls.Add(tb);
cell.Controls.Add(new LiteralControl("<br>"));
cell.Controls.Add(linkSaveQty);
row.Cells.Add(cell);
cell.VerticalAlign = VerticalAlign.Top;
}
for (int j = 3; j < 4; j++)
{
TableCell cell = new TableCell();
cell.Controls.Add(createDiv3);
createDiv3.Controls.Add(linkPrice);
row.Cells.Add(cell);
cell.VerticalAlign = VerticalAlign.Top;
}
for (int j = 4; j < 5; j++)
{
TableCell cell = new TableCell();
cell.Controls.Add(createDiv2);
createDiv2.Controls.Add(linkSubTotal);
row.Cells.Add(cell);
cell.VerticalAlign = VerticalAlign.Top;
}
for (int j = 5; j < 6; j++)
{
imgLinkDelete.ImageUrl = "../../images/delete.png";
TableCell cell = new TableCell();
cell.Controls.Add(imgLinkDelete);
row.Cells.Add(cell);
cell.VerticalAlign = VerticalAlign.Top;
}
table.Rows.Add(row);
}
TextBoxIdCollection = collection;
PanelItemsCart.Controls.Add(table);
con2.Close();
}
con2.Close();
//...................................Product Listing...............................
}
This was my code for loading dynamic controls on page load event. Here is the Enumeration string and click event of the dynamically created link button, which is not working.
private List<string> TextBoxIdCollection
{
get
{
var collection = ViewState["TextBoxIdCollection"] as List<string>;
return collection ?? new List<string>();
}
set { ViewState["TextBoxIdCollection"] = value; }
}
void OnDynamicLinkButtonClickSave(object sender, CommandEventArgs e)
{
LinkButton clickedButton = (LinkButton)sender;
String commandArgument = clickedButton.CommandArgument;
int value = 0;
foreach (Control c in PanelItemsCart.Controls)
{
if (c.GetType() == typeof(TextBox) && c.ID == (commandArgument))
{
value = Convert.ToInt32(((TextBox)c).Text);
con4.Close();
con4.Open();
SqlDataAdapter adp = new SqlDataAdapter("select * from db_temporary_cart where((IP_address='" + Request.QueryString["ip"].ToString() + "' AND date='" + DateTime.Now.ToShortDateString() + "') AND (product_id='" + commandArgument + "'))", con4);
DataSet ds = new DataSet();
adp.Fill(ds, "db_temporary_cart");
int cd = ds.Tables[0].Rows.Count;
if (cd > 0)
{
int sendQty = value;
con4.Close();
con3.Close();
con3.Open();
SqlCommand cmd4 = new SqlCommand("UPDATE db_temporary_cart SET quantity='" + sendQty + "' where((IP_address='" + Request.QueryString["ip"].ToString() + "' AND date='" + DateTime.Now.ToShortDateString() + "') AND (product_id='" + commandArgument + "'))", con3);
cmd4.ExecuteNonQuery();
con3.Close();
}
con4.Close();
PanelItemsCart.Controls.Clear();
productListing();
}
}
}
Kindly, help me enter all the textboxes' and labels', which are dynamically created, values in the database on click event of dynamically created linkbuttons.

C#.net how to add an image into a table cell dynamically by code

I am trying to add an image into a table that I'm making dynamically by code behind.
However the image is not added to the cell.
All the other codes I'm finding are talking about an htmltable which is not the same as table();
public partial class Children_nihul_1 : System.Web.UI.Page
{
protected string mychildrenlist;
protected void Page_Init(object sender, EventArgs e)
{
var cases = new List<string>();
System.Web.UI.WebControls.Image myGamepic1 = new System.Web.UI.WebControls.Image();
// var myGamepic1 = new Image();
myGamepic1.ImageUrl = "~/img/inner-page/Game1.png";
myGamepic1.Height = 30;
//this part is only a call for data from database- not relavent to the
qustion./
DataSet ds = new DataSet();
string x = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("./App_Data/DatabaseGames.accdb") + ";";
string y = "select * from Students";
mySql myq = new mySql();
ds = myq.sqlRet(x, y);
rowlist = ds.Tables[0].Rows.Count;
for (int i = 0; i < rowlist; ++i)
{
cases.Add(ds.Tables[0].Rows[i][1].ToString());
}
//my table creation
Table table = new Table();
table.BorderStyle = BorderStyle.None;
//Add Header Row
TableRow row = new TableRow();
TableHeaderCell headerCell = new TableHeaderCell();
headerCell.Text = "aaa";
row.Controls.Add(headerCell);
headerCell = new TableHeaderCell();
headerCell.Text = "ccc";
row.Controls.Add(headerCell);
table.Controls.Add(row);
for (int i = 0; i < rowlist; ++i)
{
//Add DataRow
row = new TableRow();
TableCell cell = new TableCell();
cell.Text = cases[i];
row.Controls.Add(cell);
cell = new TableCell();
cell.Controls.Add(myGamepic1);
row.Controls.Add(cell);
table.Controls.Add(row);
}
Panel1.Controls.Add(table);
Panel1.Controls.Add(myGamepic1);
}
}
Try something like this. Works for me when adding an image dynamic using code behind.
cell11.Text = string.Format("<img src='images/close_icon.png' />");

asp.net c# adding multiple tablerows to table only results in one row

I have to add a selection of data from the database to a table dynamically. To do so I have created a table that has rows added to it in a loop. However it only really adds the final row. I assume it's something to do with the naming? Below is the code I'm using. It returns the table, formatted correctly with the header, but only one row of data...
protected Table listVolunteers()
{
// Query to get volunteer information
string query = "SELECT gvo_id, gvo_name, gvo_email, gvo_mobile_ph, gvo_dob, gvo_status FROM volunteer";
// Table will hold the following information on volunteers:
// ID, Name, Email, Mobile, DOB, Status
// As well as a check box to do mass delete, a view button and an edit button on each
Table result = new Table();
result.ID = "volunteers";
result.CssClass = "list";
result.CellSpacing = 0;
// Creater table header
TableHeaderRow header = new TableHeaderRow();
header.CssClass = "header";
TableHeaderCell id = new TableHeaderCell();
id.CssClass = "id";
id.Width = 10;
id.Text = "ID";
header.Cells.Add(id);
TableHeaderCell name = new TableHeaderCell();
name.CssClass = "name";
name.Text = "NAME";
header.Cells.Add(name);
TableHeaderCell email = new TableHeaderCell();
email.CssClass = "email";
email.Text = "EMAIL";
header.Cells.Add(email);
TableHeaderCell mobile = new TableHeaderCell();
mobile.CssClass = "mobile";
mobile.Width = 70;
mobile.Text = "MOBILE #";
header.Cells.Add(mobile);
TableHeaderCell dob = new TableHeaderCell();
dob.CssClass = "dob";
dob.Width = 50;
dob.Text = "D.O.B";
header.Cells.Add(dob);
TableHeaderCell status = new TableHeaderCell();
status.CssClass = "status";
status.Width = 50;
status.Text = "STAT";
header.Cells.Add(status);
TableHeaderCell check = new TableHeaderCell();
check.CssClass = "check";
check.Width = 13;
header.Cells.Add(check);
TableHeaderCell view = new TableHeaderCell();
view.CssClass = "button";
view.Width = 50;
header.Cells.Add(view);
TableHeaderCell edit = new TableHeaderCell();
edit.CssClass = "button";
edit.Width = 50;
header.Cells.Add(edit);
// Add header to table
result.Rows.Add(header);
//Declaration for following code
TableCell rid = new TableCell();
rid.CssClass = "id";
TableCell rname = new TableCell();
rname.CssClass = "name";
TableCell remail = new TableCell();
remail.CssClass = "email";
TableCell rmobile = new TableCell();
rmobile.CssClass = "mobile";
TableCell rdob = new TableCell();
rdob.CssClass = "dob";
TableCell rstatus = new TableCell();
rstatus.CssClass = "status";
TableCell rcheck = new TableCell();
rcheck.CssClass = "check";
TableCell rview = new TableCell();
rview.CssClass = "button";
TableCell redit = new TableCell();
redit.CssClass = "button";
CheckBox chk = new CheckBox();
chk.Checked = false;
Button btnView = new Button();
btnView.Text = "View";
Button btnEdit = new Button();
btnEdit.Text = "Edit";
string rowClass = "odd";
Vector<TableRow> rows = new Vector<TableRow>();
// Add volunteers to table
try
{
using (conn)
{
conn.Open();
cmd = new OleDbCommand(query, conn);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
DateTime temp = new DateTime();
rid.Text = rdr.GetValue(0).ToString();
rname.Text = rdr.GetValue(1).ToString();
remail.Text = rdr.GetValue(2).ToString();
rmobile.Text = rdr.GetValue(3).ToString();
DateTime.TryParse(rdr.GetValue(4).ToString(), out temp);
rdob.Text = temp.ToString("dd/MM/yy");
rstatus.Text = rdr.GetValue(5).ToString();
chk.ID = rid.Text;
btnView.PostBackUrl = string.Format("/VolunteerView.aspx?ID={0}", rid.Text);
btnEdit.PostBackUrl = string.Format("/VolunteerEdit.aspx?ID={0}", rid.Text);
rcheck.Controls.Add(chk);
rview.Controls.Add(btnView);
redit.Controls.Add(btnEdit);
TableRow row = new TableRow();
if (rowClass == "even")
rowClass = "odd";
else
rowClass = "even";
row.CssClass = rowClass;
// Add cells to row
row.Cells.Add(rid);
row.Cells.Add(rname);
row.Cells.Add(remail);
row.Cells.Add(rmobile);
row.Cells.Add(rdob);
row.Cells.Add(rstatus);
row.Cells.Add(rcheck);
row.Cells.Add(rview);
row.Cells.Add(redit);
// Add row to table
rows.Add(row);
}
TableRow[] array = new TableRow[rows.Count];
for (int i = 0; i < rows.Count; i++)
{
array[i] = rows[i];
}
result.Rows.AddRange(array);
}
}
catch (Exception e)
{
TableCell error = new TableCell();
TableRow row = new TableRow();
error.ColumnSpan = 9;
error.CssClass = "error";
error.Text = "An error occurred while loading the volunteers";
row.Cells.Add(error);
result.Rows.Add(row);
}
finally
{
if (rdr != null)
rdr.Close();
}
if (conn != null)
conn.Close();
return result;
}
Try using the ImportRow method()
result.ImportRow(row);
You can replace where you are doing the following :
// Add row to table
rows.Add(row);
And use the ImportRow method. That's all there is to it, you should not need further code.
Okay so I solved the problem thanks to this post.
Pretty much all I had to do was ensure I was creating a new row / cell in the loop. To show you what I mean, the following shows my now functioning loop.
while (rdr.Read())
{
DateTime temp = new DateTime();
// This is the code that was added in.
rid = new TableCell();
rname = new TableCell();
remail = new TableCell();
rmobile = new TableCell();
rdob = new TableCell();
rstatus = new TableCell();
rcheck = new TableCell();
rview = new TableCell();
redit = new TableCell();
chk = new CheckBox();
btnView = new Button();
btnEdit = new Button();
// Because I was creating new controls I also had to move my css classes to the loop as well
rid.CssClass = "id";
rname.CssClass = "name";
remail.CssClass = "email";
rmobile.CssClass = "mobile";
rdob.CssClass = "dob";
rstatus.CssClass = "status";
rcheck.CssClass = "check";
rview.CssClass = "button";
redit.CssClass = "button";
chk.Checked = false;
btnView.Text = "View";
btnEdit.Text = "Edit";
rid.Text = rdr.GetValue(0).ToString();
rname.Text = rdr.GetValue(1).ToString();
remail.Text = rdr.GetValue(2).ToString();
rmobile.Text = rdr.GetValue(3).ToString();
DateTime.TryParse(rdr.GetValue(4).ToString(), out temp);
rdob.Text = temp.ToString("dd/MM/yy");
rstatus.Text = rdr.GetValue(5).ToString();
chk.ID = rid.Text;
btnView.PostBackUrl = string.Format("/VolunteerView.aspx?ID={0}", rid.Text);
btnEdit.PostBackUrl = string.Format("/VolunteerEdit.aspx?ID={0}", rid.Text);
rcheck.Controls.Add(chk);
rview.Controls.Add(btnView);
redit.Controls.Add(btnEdit);
row = new TableRow();
if (rowClass == "even")
rowClass = "odd";
else
rowClass = "even";
row.CssClass = rowClass;
// Add cells to row
row.Cells.Add(rid);
row.Cells.Add(rname);
row.Cells.Add(remail);
row.Cells.Add(rmobile);
row.Cells.Add(rdob);
row.Cells.Add(rstatus);
row.Cells.Add(rcheck);
row.Cells.Add(rview);
row.Cells.Add(redit);
// Add row to table
result.Rows.Add(row);
}

Categories