How to Create Dynamically Generated TextBoxes in ASP.NET - asp.net

I have this code which generates TextBoxes in a Table dynamically, I got it from a website:
protected void AddStdBtn_Click(object sender, EventArgs e)
{
CreateDynamicTable();
}
private void CreateDynamicTable()
{
// Fetch the number of Rows and Columns for the table
// using the properties
if (ViewState["Stu"] != null)
Students = (DataTable)ViewState["Stu"];
int tblCols = 1;
int tblRows = Int32.Parse(NoTxt.Text);
// Now iterate through the table and add your controls
for (int i = 0; i < tblRows; i++)
{
TableRow tr = new TableRow();
for (int j = 0; j < tblCols; j++)
{
TableCell tc = new TableCell();
TextBox txtBox = new TextBox();
txtBox.ID = "txt-" + i.ToString() + "-" + j.ToString();
txtBox.Text = "RowNo:" + i + " " + "ColumnNo:" + " " + j;
// Add the control to the TableCell
tc.Controls.Add(txtBox);
// Add the TableCell to the TableRow
tr.Cells.Add(tc);
}
// Add the TableRow to the Table
tbl.Rows.Add(tr);
tbl.EnableViewState = true;
ViewState["tbl"] = true;
}
}
protected void CalculateBtn_Click(object sender, EventArgs e)
{
foreach (TableRow tr in tbl.Controls)
{
foreach (TableCell tc in tr.Controls)
{
if (tc.Controls[0] is TextBox)
{
Response.Write(((TextBox)tc.Controls[0]).Text);
}
}
Response.Write("<br/>");
}
}
protected override object SaveViewState()
{
object[] newViewState = new object[2];
List<string> txtValues = new List<string>();
foreach (TableRow row in tbl.Controls)
{
foreach (TableCell cell in row.Controls)
{
if (cell.Controls[0] is TextBox)
{
txtValues.Add(((TextBox)cell.Controls[0]).Text);
}
}
}
newViewState[0] = txtValues.ToArray();
newViewState[1] = base.SaveViewState();
return newViewState;
}
protected override void LoadViewState(object savedState)
{
//if we can identify the custom view state as defined in the override for SaveViewState
if (savedState is object[] && ((object[])savedState).Length == 2 && ((object[])savedState)[0] is string[])
{
object[] newViewState = (object[])savedState;
string[] txtValues = (string[])(newViewState[0]);
if (ViewState["Stu"] != null)
Students = (DataTable)ViewState["Stu"];
if (txtValues.Length > 0)
{
//re-load tables
CreateDynamicTable();
int i = 0;
foreach (TableRow row in tbl.Controls)
{
foreach (TableCell cell in row.Controls)
{
if (cell.Controls[0] is TextBox && i < txtValues.Length)
{
((TextBox)cell.Controls[0]).Text = txtValues[i++].ToString();
}
}
}
}
//load the ViewState normally
base.LoadViewState(newViewState[1]);
}
else
{
base.LoadViewState(savedState);
}
}
Now if you examine CreateDynamicTable() function, particularly the line:
int tblRows = Int32.Parse(NoTxt.Text);
you can see that the user can control the number of rows by entering a number in the TextBox NoTxt. When I run this code I get the following error:
An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code
Additional information: Input string was not in a correct format.
and the error location is in the same line above.
The question is: How can I let the user control the number of rows in the table?

After few days of reading and research, the solution can be done by using Session variables. Store the value obtained in NoTxt.Text as follows for example:
Session["V"] = Int32.Parse(NoTxt.Text);
and retrieve it once you need it.

Related

how to get value from dynamically created textbox in asp.net

hi i'm Cannot get value dynamically created textbox and save into database. plz help
his is code which I have created in this code text box are created but when I will input the value in the text and retrieve the value from dynamically created text box it give error
protected void btnAtt_Click(object sender, EventArgs e)
{
int DPLID = int.Parse(DPLCategory.Text);
var query = (from p in database.tbl_Attributes
where p.ProductTypeId_FK == DPLID
select new
{
p.Attribute_Id,
p.AttributeName,
p.ProductTypeId_FK,
}).ToArray();
for (int i = 0; i < query.Count(); i++)
{
Label lblatt = new Label();
lblatt.ID = query[i].AttributeName;
lblatt.Text = query[i].AttributeName + " : ";
lblatt.CssClass = "control-label";
TextBox txtatt = new TextBox();
txtatt.ID = "txtatt"+i;
txtatt.Attributes.Add("runat", "server");
txtatt.Text = String.Empty;
txtatt.CssClass = "form-control input-sm";
HtmlTextWriterTag.Br.ToString();
Place1.Controls.Add(lblatt);
HtmlTextWriterTag.Br.ToString();
Place1.Controls.Add(txtatt);
HtmlTextWriterTag.Br.ToString();
}
}
protected void lbtnSave_Click(object sender, EventArgs e)
{
int DPLID = int.Parse(DPLCategory.Text);
var query = (from p in database.tbl_Attributes
where p.ProductTypeId_FK == DPLID
select new
{
p.Attribute_Id,
p.AttributeName,
p.ProductTypeId_FK,
}).ToArray();
int LastId = database.tbl_Products.Max(p => p.ProductId);
for (int i = 0; i < query.Count(); i++)
{
database.tbl_ProductValue.Add(new Models.tbl_ProductValue()
{
ProductId_FK = LastId,
AttributeID_FK = query[i].Attribute_Id,
ProductValue = ??,
});
database.SaveChanges();
}
}
plz help me for how to get textbox?
I haven't worked with WebForms in a while but you can access the controls by their IDs like this:
ProductValue = ((TextBox)FindControl("txtatt" + i)).Text;

Custom GridView Server Control DataBind causes duplicate control ID's error

OK. I've long used this site as a reference, but I've now hit a wall of my own.
I am creating a custom server control which inherits from the System.Web.UI.WebControls.GridView class. It's purpose is simply to display a grid with a very defined format. It binds and loads the data fine, but trying to activate any of the paging throws an exception saying "Multiple controls with the same ID 'lblHdrText_2' were found. FindControl requires that controls have unique IDs.".
I could just throw the event out to the user and let them do the paging, but one of the goals was to have this control be able to handle its own paging, just like the GridView control already does.
I'm having the same problem for sorting and altering the page size as well. Basically anytime I call "DataBind" within the control after it has already been rendered.
Here's the code to handle those events:
protected void OnFirstPageClicked(EventArgs e)
{
if (this.FirstPageClicked != null)
this.FirstPageClicked.Invoke(this, e);
GridViewPageEventArgs pgea = new GridViewPageEventArgs(0);
this.OnPageIndexChanging(pgea);
if (pgea.Cancel)
return;
this.PageIndex = 0;
this.RefreshData();
this.OnPageIndexChanged(e);
}
protected void OnLastPageClicked(EventArgs e)
{
if (this.LastPageClicked != null)
this.LastPageClicked.Invoke(this, e);
GridViewPageEventArgs pgea = new GridViewPageEventArgs(this.PageCount - 1);
this.OnPageIndexChanging(pgea);
if (pgea.Cancel)
return;
this.PageIndex = this.PageCount - 1;
this.RefreshData();
this.OnPageIndexChanged(e);
}
protected void OnPreviousPageClicked(EventArgs e)
{
if (this.PageIndex > 0)
{
if (this.PreviousPageClicked != null)
this.PreviousPageClicked.Invoke(this, e);
GridViewPageEventArgs pgea = new GridViewPageEventArgs(this.PageIndex++);
this.OnPageIndexChanging(pgea);
if (pgea.Cancel)
return;
this.PageIndex--;
this.RefreshData();
this.OnPageIndexChanged(e);
}
}
protected void OnNextPageClicked(EventArgs e)
{
if (this.PageIndex < this.PageCount - 1)
{
if (this.NextPageClicked != null)
this.NextPageClicked.Invoke(this, e);
GridViewPageEventArgs pgea = new GridViewPageEventArgs(this.PageIndex++);
this.OnPageIndexChanging(pgea);
if (pgea.Cancel)
return;
this.PageIndex++;
this.RefreshData();
this.OnPageIndexChanged(e);
}
}
protected void OnPageSizeChanged(EventArgs e)
{
this.RefreshData();
if (this.PageSizeChanged != null)
this.PageSizeChanged.Invoke(this, e);
}
protected override void OnDataBound(EventArgs e)
{
base.OnDataBound(e);
}
private void RefreshData()
{
this.DataBind();
}
private void imgPg_OnCommand(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "FirstPage":
this.OnFirstPageClicked(EventArgs.Empty);
break;
case "LastPage":
this.OnLastPageClicked(EventArgs.Empty);
break;
case "PrevPage":
this.OnPreviousPageClicked(EventArgs.Empty);
break;
case "NextPage":
this.OnNextPageClicked(EventArgs.Empty);
break;
}
}
private void drpPageSz_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList drpPgSz = (sender as DropDownList);
if (drpPgSz != null)
{
this.PageSize = int.Parse(drpPgSz.SelectedValue);
this.OnPageSizeChanged(e);
}
else
throw new Exception("Unable to determine page size: cannot cast sender as DropDownList.");
}
The actual event handlers are at the bottom. The "RefreshData" method is just there because I was experimenting with different ways of clearing the controls from the grid before I called "DataBind". So far, everything I've tried results in the entire grid not rendering after postback.
I am doing quite a bit with the Render and CreateChildControls, but the header generation itself is completely internal to the System.Web.UI.WebControls.GridView control. Here's my rendering code, if it helps at all:
protected override void OnPreRender(EventArgs e)
{
Control link = this.Page.Header.FindControl("CustomGridViewCss");
if (link == null)
{
System.Web.UI.HtmlControls.HtmlLink newLink = new System.Web.UI.HtmlControls.HtmlLink();
newLink.ID = "CustomGridViewCss";
newLink.Attributes.Add("href", this.Page.ClientScript.GetWebResourceUrl(typeof(ITCWebToolkit.Web.UI.Controls.GridView), "ITCWebToolkit.Web.UI.Controls.style.CustomGridView.css"));
newLink.Attributes.Add("type", "text/css");
newLink.Attributes.Add("rel", "stylesheet");
this.Page.Header.Controls.Add(newLink);
}
base.OnPreRender(e);
this.EnsureChildControls();
}
protected override void Render(HtmlTextWriter writer)
{
if (this._imgFPg != null)
this.Page.ClientScript.RegisterForEventValidation(this._imgFPg.UniqueID);
if (this._imgPrevPg != null)
this.Page.ClientScript.RegisterForEventValidation(this._imgPrevPg.UniqueID);
if (this._imgNextPg != null)
this.Page.ClientScript.RegisterForEventValidation(this._imgNextPg.UniqueID);
if (this._imgLastPg != null)
this.Page.ClientScript.RegisterForEventValidation(this._imgLastPg.UniqueID);
if (this._drpPageSz != null)
this.Page.ClientScript.RegisterForEventValidation(this._drpPageSz.UniqueID);
if (this.HeaderRow != null)
for (int i = 1; i < this.HeaderRow.Cells.Count - 2; i++)
if (i < this.Columns.Count && this.Columns[i] is SortableField && ((this.Columns[i] as SortableField).ShowSort))
{
ImageButton img = (this.HeaderRow.Cells[i].FindControl("imgSort_" + i.ToString()) as ImageButton);
if (img != null)
this.Page.ClientScript.RegisterForEventValidation(img.UniqueID);
}
base.Render(writer);
}
protected override Table CreateChildTable()
{
this.PagerSettings.Visible = false;
this.GridLines = GridLines.None;
Table tbl = base.CreateChildTable();
tbl.Attributes.Add("name", this.UniqueID);
return tbl;
}
protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding)
{
this.GridLines = GridLines.None;
int iCount = base.CreateChildControls(dataSource, dataBinding);
// Modify footer row
System.Web.UI.WebControls.GridViewRow ftr = this.FooterRow;
// NOTE: We're modifying the footer first, because we're looking at the
// total number of rows in the header for the ColSpan property we
// use in the footer and we want the row count *before* we modify
// the header.
ftr.Cells.Clear();
this.BuildFooter(this.FooterRow);
// Modify Header Row
System.Web.UI.WebControls.GridViewRow hdr = this.HeaderRow;
hdr.CssClass = "GridViewHeader";
for (int c = 0; c < hdr.Cells.Count; c++)
{
hdr.Cells[c].CssClass = "GridViewHeaderTC";
if (c > 0)
hdr.Cells[c].Style.Add("border-left", "solid 1px #ccccd3");
if (c < this.Columns.Count && this.Columns[c] is SortableField && ((this.Columns[c] as SortableField).ShowSort))
{
hdr.Cells[c].Controls.Clear();
Label lblHdrText = new Label();
lblHdrText.ID = "lblHdrText_" + c.ToString();
lblHdrText.Text = hdr.Cells[c].Text;
hdr.Cells[c].Controls.Add(lblHdrText);
ImageButton imgSort = new ImageButton();
imgSort.ID = "imgSort_" + c.ToString();
imgSort.CssClass = "GridViewHeaderSort";
imgSort.ImageUrl = this.Page.ClientScript.GetWebResourceUrl(typeof(ITCWebToolkit.Web.UI.Controls.GridView), "ITCWebToolkit.Web.UI.Controls.images.gridView.Sort.png");
imgSort.AlternateText = "";
imgSort.CommandArgument = (this.Columns[c] as BoundField).DataField;
imgSort.CommandName = "Sort";
imgSort.Command += new CommandEventHandler(this.imgSort_OnCommand);
hdr.Cells[c].Controls.Add(imgSort);
imgSort.Attributes.Add("name", imgSort.UniqueID);
}
}
TableCell tdTL = new TableCell();
tdTL.Style.Add(HtmlTextWriterStyle.Width, "6px");
tdTL.CssClass = "GridViewHeaderTL";
hdr.Cells.AddAt(0, tdTL);
TableCell tdTR = new TableCell();
tdTR.Style.Add(HtmlTextWriterStyle.Width, "6px");
tdTR.Style.Add("border-left", "1px solid #ccccd3;");
tdTR.CssClass = "GridViewHeaderTR";
hdr.Cells.Add(tdTR);
// Modify individual rows
for (int i = 0; i < this.Rows.Count; i++)
{
System.Web.UI.WebControls.GridViewRow tr = this.Rows[i];
tr.CssClass = (i % 2 == 0) ? "GridViewLineAlt" : "GridViewLine";
for (int c = 0; c < tr.Cells.Count - 1; c++)
tr.Cells[c].Style.Add("border-right", "solid 1px #ccccd3");
TableCell tdL = new TableCell();
tdL.CssClass = "GridViewLineLeft";
tr.Cells.AddAt(0, tdL);
TableCell tdR = new TableCell();
tdR.CssClass = "GridViewLineRight";
tr.Cells.Add(tdR);
}
return iCount;
}
protected void BuildFooter(GridViewRow tr)
{
TableCell tdBL = new TableCell();
tdBL.Style.Add(HtmlTextWriterStyle.Width, "6px");
tdBL.CssClass = "GridViewFooterBL";
tr.Cells.Add(tdBL);
int colCount = this.HeaderRow.Cells.Count;
TableCell td = new TableCell();
td.ID = "tdFooterControls";
td.CssClass = "GridViewFooterBC";
td.ColumnSpan = colCount;
this._spanPgBtns = new Label();
this._spanPgBtns.ID = "spanPgButtons";
this._spanPgBtns.Style.Add("float", "right");
this._spanPgBtns.Style.Add("margin-right", "20px");
this._imgFPg = new ImageButton();
this._imgFPg.ID = "imgFPg";
this._imgFPg.CssClass = "FirstPg";
this._imgFPg.ImageUrl = this.Page.ClientScript.GetWebResourceUrl(typeof(ITCWebToolkit.Web.UI.Controls.GridView), "ITCWebToolkit.Web.UI.Controls.images.gridView.FstPg.png");
this._imgFPg.ImageAlign = ImageAlign.Middle;
this._imgFPg.CommandName = "FirstPage";
this._imgFPg.Command += new CommandEventHandler(this.imgPg_OnCommand);
this._spanPgBtns.Controls.Add(this._imgFPg);
this._imgPrevPg = new ImageButton();
this._imgPrevPg.ID = "imgPrevPg";
this._imgPrevPg.CssClass = "PrevPg";
this._imgPrevPg.ImageUrl = this.Page.ClientScript.GetWebResourceUrl(typeof(ITCWebToolkit.Web.UI.Controls.GridView), "ITCWebToolkit.Web.UI.Controls.images.gridView.PrevPg.png");
this._imgPrevPg.ImageAlign = ImageAlign.Middle;
this._imgPrevPg.CommandName = "PrevPage";
this._imgPrevPg.Command += new CommandEventHandler(this.imgPg_OnCommand);
this._spanPgBtns.Controls.Add(this._imgPrevPg);
Label lblPageNum = new Label();
lblPageNum.ID = "lblPageNum";
lblPageNum.Width = new Unit("50px");
lblPageNum.Text = string.Format("{0} / {1}", this.PageIndex + 1, this.PageCount);
lblPageNum.Style.Add(HtmlTextWriterStyle.TextAlign, "center");
this._spanPgBtns.Controls.Add(lblPageNum);
this._imgNextPg = new ImageButton();
this._imgNextPg.ID = "imgNextPg";
this._imgNextPg.CssClass = "NextPg";
this._imgNextPg.ImageUrl = this.Page.ClientScript.GetWebResourceUrl(typeof(ITCWebToolkit.Web.UI.Controls.GridView), "ITCWebToolkit.Web.UI.Controls.images.gridView.NextPg.png");
this._imgNextPg.ImageAlign = ImageAlign.Middle;
this._imgNextPg.CommandName = "NextPage";
this._imgNextPg.Command += new CommandEventHandler(this.imgPg_OnCommand);
this._spanPgBtns.Controls.Add(this._imgNextPg);
this._imgLastPg = new ImageButton();
this._imgLastPg.ID = "imgLastPg";
this._imgLastPg.CssClass = "LastPg";
this._imgLastPg.ImageUrl = this.Page.ClientScript.GetWebResourceUrl(typeof(ITCWebToolkit.Web.UI.Controls.GridView), "ITCWebToolkit.Web.UI.Controls.images.gridView.LstPg.png");
this._imgLastPg.ImageAlign = ImageAlign.Middle;
this._imgLastPg.CommandName = "LastPage";
this._imgLastPg.Command += new CommandEventHandler(this.imgPg_OnCommand);
this._spanPgBtns.Controls.Add(this._imgLastPg);
td.Controls.Add(this._spanPgBtns);
Label spanPageSz = new Label();
spanPageSz.ID = "spanPageSz";
spanPageSz.Style.Add("margin-left", "20px");
this._drpPageSz = new DropDownList();
this._drpPageSz.ID = "drpPageSzSelect";
this._drpPageSz.AutoPostBack = true;
this._drpPageSz.SelectedIndexChanged += new EventHandler(drpPageSz_SelectedIndexChanged);
this._drpPageSz.Items.Add(new ListItem("10", "10"));
this._drpPageSz.Items.Add(new ListItem("25", "25"));
this._drpPageSz.Items.Add(new ListItem("50", "50"));
this._drpPageSz.Items.Add(new ListItem("100", "100"));
spanPageSz.Controls.Add(this._drpPageSz);
td.Controls.Add(spanPageSz);
Label lblRecVis = new Label();
lblRecVis.ID = "lblRecordsCount";
lblRecVis.Style.Add("margin-left", "20px");
lblRecVis.Text = string.Format("Displaying {0} of {1} records.", Math.Min(this.PageSize, this.Rows.Count - (this.PageIndex * this.PageSize)), this.Rows.Count);
lblRecVis.Text = "Total Record Display";
td.Controls.Add(lblRecVis);
tr.Cells.Add(td);
TableCell tdBR = new TableCell();
tdBR.Style.Add(HtmlTextWriterStyle.Width, "6px");
tdBR.CssClass = "GridViewFooterBR";
tr.Cells.Add(tdBR);
this._imgFPg.Attributes.Add("name", this._imgFPg.UniqueID);
this._imgPrevPg.Attributes.Add("name", this._imgPrevPg.UniqueID);
this._imgNextPg.Attributes.Add("name", this._imgNextPg.UniqueID);
this._imgLastPg.Attributes.Add("name", this._imgLastPg.UniqueID);
this._drpPageSz.Attributes.Add("name", this._drpPageSz.UniqueID);
}
I'm only about 6/10 on custom server controls, so I'm sure there's at least one thing I'm doing wrong here :)
Thanks in advance for any help!
OK. I finally found a reference and answered my own question. The trick is in overriding the "PerformSelect" method and handling DataSource vs DataSourceID there.
Details on how to do this can be found on this MSDN page:
http://msdn.microsoft.com/en-us/library/ms366539(v=vs.90).aspx
Look for the section titled "Initiate Data Retrieval" a little over half-way down.

Unable to serialize the session state

i am tired wondering the issue for this problem. have read so many blogs and forums for this but i am not able to find out the problem.
I am using "SQLServer" mode to store session.
Everything is working fine. But whenever i use search function in my website, it throws the below error:
"Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode."
I am assuming that this is because of the paging code i have used on that page. That code is as below:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select xxxxqueryxxxx";
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
try
{
using (con)
{
con.Open();
da.Fill(ds);
}
}
catch
{
ds = null;
}
finally
{
if (ds != null)
{
CustomPaging page = new CustomPaging();
DataTable dt = ds.Tables[0];
page.PageSize = 10;
page.DataSource = dt;
page.CurrentPageIndex = 0;
no = 1;
Session["DT"] = dt;
Session["page"] = page;
bindData(page, dt);
//set these properties for multi columns in datalist
DataList2.RepeatColumns = 1;
DataList2.RepeatDirection = RepeatDirection.Horizontal;
}
}
}
}
void bindData(CustomPaging page, DataTable dt)
{
try
{
DataList2.DataSource = page.DoPaging;
DataList2.DataBind();
//DataList2.DataSource = SqlDataSource1;
//DataList2.DataBind();
lbtnPre.Enabled = !page.IsFirstPage; //Enable / Disable Navigation Button
// lbtnPre.CssClass = "disabledbtn";
lbtnNext.Enabled = !page.IsLastPage;
//lbtnNext.CssClass = "disabledbtn";
lblStatus.Text = NavigationIndicator(); //Build Navigation Indicator
//for creating page index
DataTable dt1 = new DataTable();
dt1.Columns.Add("PageIndex");
dt1.Columns.Add("PageText");
for (int i = 0; i < page.PageCount; i++)
{
DataRow dr = dt1.NewRow();
dr[0] = i;
dr[1] = i + 1;
dt1.Rows.Add(dr);
}
dlPaging.DataSource = dt1;
dlPaging.DataBind();
dlPaging.RepeatColumns = 10;
dlPaging.RepeatDirection = RepeatDirection.Horizontal;
}
catch (Exception)
{
}
finally
{
page = null;
}
}
string NavigationIndicator()
{
string str = string.Empty; //Page x Of Y
str = Convert.ToString(((CustomPaging)Session["page"]).CurrentPageIndex + 1) + " of " + ((CustomPaging)Session["PAGE"]).PageCount.ToString() + " Page(s) found";
return str;
}
protected void lbtnPre_Click(object sender, EventArgs e)
{
int pageIndex = ((CustomPaging)Session["page"]).CurrentPageIndex;
if (!((CustomPaging)Session["page"]).IsFirstPage)
//Decrements the pageIndex by 1 (Move to Previous page)
((CustomPaging)Session["page"]).CurrentPageIndex -= 1;
else
((CustomPaging)Session["page"]).CurrentPageIndex = pageIndex;
//Binds the DataList with new pageIndex
bindData(((CustomPaging)Session["page"]), ((DataTable)Session["DT"]));
}
protected void lbtnNext_Click(object sender, EventArgs e)
{
int pageIndex = ((CustomPaging)Session["page"]).CurrentPageIndex;
if (!((CustomPaging)Session["page"]).IsLastPage)
//Increments the pageIndex by 1 (Move to Next page)
((CustomPaging)Session["page"]).CurrentPageIndex += 1;
else
((CustomPaging)Session["page"]).CurrentPageIndex = pageIndex;
//Binds the DataList with new pageIndex
bindData(((CustomPaging)Session["page"]), ((DataTable)Session["DT"]));
}
protected void DataList2_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect("Default2.aspx?partnumber=" + DataList2.DataKeyField[DataList2.SelectedIndex].ToString());
}
protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "Select")
{
no = int.Parse(e.CommandArgument.ToString()) + 1;
((CustomPaging)Session["page"]).CurrentPageIndex = int.Parse(e.CommandArgument.ToString());
//Binds the DataList with new pageIndex
bindData(((CustomPaging)Session["page"]), ((DataTable)Session["DT"]));
}
}
protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
{
LinkButton btn = (LinkButton)e.Item.FindControl("lnkbtnPaging");
if (btn.Text == no.ToString())
{
btn.ForeColor = System.Drawing.Color.Maroon;
btn.Font.Underline = false;
}
else
{
btn.ForeColor = System.Drawing.Color.DarkCyan;
btn.Font.Underline = false;
}
}
I just want to know what the problem is in the coding and "how to serialize the session"?
What shold i do to improve the coding?
Any help will be appreciated.
Thank You
I guess your custom paging control is not serializable. This must be the cause of the issue.
Anyway, storing a control in session is not a good idea. Just store the few serializable properties which enable to rebuild the control (PageSize and CurrentPageIndex), or pass them in query string for example.
You could also use ViewState if you can
About storing the DataTable in Session, this might be a really bad idea if you have a lot of data and many connected users.

Deleting records from table

In the above photo I have a table containing a list of users that are add dynamically in the table.
I want when I click on the red-cross image button the corresponding user to be deleted from the database.
Here is the code that fills the table:
/****** Filling the originators table ********/
string[] oa1 = originator;
for (int i = 0; i < oa1.Length; i++)
{
TableRow row = new TableRow();
users_table.Rows.Add(row);
for (int colCount = 0; colCount < 4; colCount++)
{
TableCell cell = new TableCell();
row.Cells.Add(cell);
if (colCount == 0)
{
cell.Controls.Add(new LiteralControl(oa1[i]));
}
else if (colCount == 1)
{
cell.Controls.Add(new LiteralControl("|"));
}
else if (colCount == 2)
{
LLKB userInfo = new LLKB();
cell.Controls.Add(new LiteralControl(userInfo.InfoGetter(oa1[i].Trim(), "name")));
}
else if (colCount == 3)
{
ImageButton btn = new ImageButton();
btn.ImageUrl = "img/DeleteRed.png";
btn.ID = oa1[i] + "_" + i;
btn.Click += new ImageClickEventHandler(delete_originator);
cell.Controls.Add(btn);
}
}
}
and here is the method that show do the deletion:
public void delete_originator(object sender, ImageClickEventArgs e)
{
//some code here
}
So, what do you suggest I write in the deletion method??
or if you have another idea...
you should empty table and recreate the table and get username thorugh spliting imagebutton ID
by '_',So in loop when that username come you add continue statement.
some thing like that in Delete event :
string Username=((imagebutton)sender).ID.toString().tosplit('_')[0];

gridview merge column headers

I have a gridview and I want to merge the headers of column (n) and (n+1) into one so that the output will use colspan to show a single header for columns n and n+1. I've seen several ways to do it by googling for this technique but all seem to be rather cumbersome and verbose.
I was wondering if someone had come across an elegant a short solution.
Have you seen this article "Merge Two GridView Header columns in ASP.NET"? It builds the header row as you see fit. When you do this, you'll have to explicitly build each header (i.e. if you're merging Customer First Name and Customer Last Name, you'll have to ensure you explicitly include Customer ID and Customer Address, etc. as required.)
protected void myGridView_ItemCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
//custom header.
GridView gvHeader = (GridView)sender;
GridViewRow gvHeaderRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
TableCell tc1 = new TableCell();
// First column
tc1.Text = "Merged Column1";
tc1.ColumnSpan = 2;
tc1.BackColor = System.Drawing.Color.Brown;
gvHeaderRow.Cells.Add(tc1);
// Second column
tc1 = new TableCell();
tc1.Text = "Merged Column2";
tc1.ColumnSpan = 2;
gvHeaderRow.Cells.Add(tc1);
//keep building as needed.
gvHeader.Controls[0].Controls.AddAt(0, gvHeaderRow);
}
}
i created this solution example
To run in your local system will will need to create 2 files ( one for the control and one aspx) you can either do it one project or 2 projects.
GridViewPlus ==> Control class
GridViewPlusCustomHeaderRows ==> a collection to hold custom header class
CustomHeaderEventArgs ==> Event Args when custom header row is created
aspx file ==> Test program
public class GridViewPlus : GridView
{
public event EventHandler<CustomHeaderEventArgs> CustomHeaderTableCellCreated;
private GridViewPlusCustomHeaderRows _rows;
public GridViewPlus() : base ()
{
_rows = new GridViewPlusCustomHeaderRows();
}
/// <summary>
/// Allow Custom Headers
/// </summary>
public bool ShowCustomHeader { get; set; }
[PersistenceMode(PersistenceMode.InnerDefaultProperty)]
[MergableProperty(false)]
public GridViewPlusCustomHeaderRows CustomHeaderRows
{
get {return _rows; }
}
protected virtual void OnCustomHeaderTableCellCreated(CustomHeaderEventArgs e)
{
EventHandler<CustomHeaderEventArgs> handler = CustomHeaderTableCellCreated;
// Event will be null if there are no subscribers
if (handler != null)
{
// Use the () operator to raise the event.
handler(this, e);
}
}
protected override void OnRowCreated(GridViewRowEventArgs e)
{
if (ShowCustomHeader && e.Row.RowType == DataControlRowType.Header) return;
base.OnRowCreated(e);
}
protected override void PrepareControlHierarchy()
{
//Do not show the Gridview header if show custom header is ON
if (ShowCustomHeader) this.ShowHeader = false;
base.PrepareControlHierarchy();
//Safety Check
if (this.Controls.Count == 0)
return;
bool controlStyleCreated = this.ControlStyleCreated;
Table table = (Table)this.Controls[0];
int j = 0;
if (CustomHeaderRows ==null )return ;
foreach (TableRow tr in CustomHeaderRows)
{
OnCustomHeaderTableCellCreated(new CustomHeaderEventArgs(tr,j));
table.Rows.AddAt(j, tr);
tr.ApplyStyle(this.HeaderStyle);
j++;
}
}
}
public class GridViewPlusCustomHeaderRows : System.Collections.CollectionBase
{
public GridViewPlusCustomHeaderRows()
{
}
public void Add(TableRow aGridViewCustomRow)
{
List.Add(aGridViewCustomRow);
}
public void Remove(int index)
{
// Check to see if there is a widget at the supplied index.
if (index > Count - 1 || index < 0)
// If no widget exists, a messagebox is shown and the operation
// is cancelled.
{
throw (new Exception("Index not valid"));
}
else
{
List.RemoveAt(index);
}
}
public TableRow Item(int Index)
{
// The appropriate item is retrieved from the List object and
// explicitly cast to the Widget type, then returned to the
// caller.
return (TableRow)List[Index];
}
}
public class CustomHeaderEventArgs : EventArgs
{
public CustomHeaderEventArgs(TableRow tr ,int RowNumber )
{
tRow = tr;
_rownumber = RowNumber;
}
private TableRow tRow;
private int _rownumber = 0;
public int RowNumber { get { return _rownumber; } }
public TableRow HeaderRow
{
get { return tRow; }
set { tRow = value; }
}
}
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Example1();
GridViewExtension1.CustomHeaderTableCellCreated += new EventHandler<CustomHeaderEventArgs>(GridViewExtension1_CustomHeaderTableCellCreated);
}
void GridViewExtension1_CustomHeaderTableCellCreated(object sender, CustomHeaderEventArgs e)
{
TableRow tc = (TableRow)e.HeaderRow;
tc.BackColor = System.Drawing.Color.AliceBlue;
}
private void Example1()
{
System.Data.DataTable dtSample = new DataTable();
DataColumn dc1 = new DataColumn("Column1",typeof(string));
DataColumn dc2 = new DataColumn("Column2",typeof(string));
DataColumn dc3 = new DataColumn("Column3",typeof(string));
DataColumn dc4 = new DataColumn("Column4",typeof(string));
// DataColumn dc5 = new DataColumn("Column5",typeof(string));
dtSample.Columns.Add(dc1);
dtSample.Columns.Add(dc2);
dtSample.Columns.Add(dc3);
dtSample.Columns.Add(dc4);
// dtSample.Columns.Add(dc5);
dtSample.AcceptChanges();
for (int i = 0; i < 25; i++)
{
DataRow dr = dtSample.NewRow();
for (int j = 0; j < dtSample.Columns.Count; j++)
{
dr[j] = j;
}
dtSample.Rows.Add(dr);
}
dtSample.AcceptChanges();
//GridViewExtension1.ShowHeader = false;
GridViewExtension1.ShowCustomHeader = true;
/*
*=======================================================================
* |Row 1 Cell 1 | Row 1 Col 2 (Span=2) | Row 1 Col 3 |
* | | | |
*=======================================================================
* |Row 2 Cell 1 | | | |
* | | Row 2 Col 2 | Row 2 Col 3 |Row 2 Col 4 |
*=======================================================================
*
*
*
*
* */
// SO we have to make 2 header row as shown above
TableRow TR1 = new TableRow();
TableCell tcR1C1 = new TableCell();
tcR1C1.Text = "Row 1 Cell 1";
tcR1C1.ColumnSpan = 1;
TR1.Cells.Add(tcR1C1);
TableCell tcR1C2 = new TableCell();
tcR1C2.Text = "Row 1 Cell 2";
tcR1C2.ColumnSpan = 2;
TR1.Cells.Add(tcR1C2);
TableCell tcR1C3 = new TableCell();
tcR1C3.Text = "Row 1 Cell 3";
tcR1C3.ColumnSpan = 1;
TR1.Cells.Add(tcR1C3);
GridViewExtension1.CustomHeaderRows.Add(TR1);
TableRow TR2 = new TableRow();
TableCell tcR2C1 = new TableCell();
tcR2C1.Text = "Row 2 Cell 1";
tcR2C1.ColumnSpan = 1;
TR2.Cells.Add(tcR2C1);
TableCell tcR2C2 = new TableCell();
tcR2C2.Text = "Row 2 Cell 2";
tcR2C2.ColumnSpan = 1;
TR2.Cells.Add(tcR2C2);
TableCell tcR2C3 = new TableCell();
tcR2C3.Text = "Row 2 Cell 3";
tcR2C3.ColumnSpan = 1;
TR2.Cells.Add(tcR2C3);
TableCell tcR2C4 = new TableCell();
tcR2C4.Text = "Row 2 Cell 4";
tcR2C4.ColumnSpan = 1;
TR2.Cells.Add(tcR2C4);
GridViewExtension1.CustomHeaderRows.Add(TR2);
GridViewExtension1.DataSource = dtSample;
GridViewExtension1.DataBind();
}
}

Resources