Dynamically Generated DropDownList web controls hides on selected - c#

I am facing troubles in creation of dynamic web controls. I have a SQL Databounded DropDownlist with DataTextField ="All_Columns" and DataValueField="DATA_TYPE".
Upon DropDownList1_SelectedIndexChanged i must check for the datatype as decimal or Varchar for the Selected value. If it is decimal i must call Createdynamicwebcontrols_decimal() and create DropDownList2. If it is varchar i must call Createdynamicwebcontrols_varchar().
Current Issue: Upon DropDownList2_SelectedIndexChanged i must create two dynamic textboxes and input values must be retained and search and display the data in a JQGrid with the help of Button Click event. But the DDL control hides completely
How to achieve above all features. Help needed please. New to dynamic web controls.
Aspx Code:
<asp:DropDownList ID="DropDownList5" runat="server" DataSourceID="column_list_for_filter" DataTextField="All_Columns" DataValueField="DATA_TYPE" OnSelectedIndexChanged ="DropDownList5_SelectedIndexChanged" AutoPostBack="true" >
</asp:DropDownList>
<asp:SqlDataSource ID="column_list_for_filter" runat="server" ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString %>" SelectCommand="SELECT COLUMN_NAME AS 'All_Columns', DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE (TABLE_NAME = 'TABLE')"></asp:SqlDataSource>
C# code:
protected void Page_Load(object sender, EventArgs e)
{
Panel6.Visible = false;
JQGrid9.Visible = false;
if (Session["DataforSearch"] != null)
{
Panel6.Visible = true;
JQGrid9.Visible = true;
JQGrid9.DataSource = Session["DataforSearch"] as string;
}
}
protected void Page_PreInit(object sender, EventArgs e)
{
//How to Proceed
}
protected void DropDownList5_SelectedIndexChanged(object sender, EventArgs e)
{
if(DropDownList5.SelectedValue == "decimal")
{
createdynamiccontrols_decimal();
}
else if(DropDownList5.SelectedValue == "int")
{
createdynamiccontrols_int();
}
else if(DropDownList5.SelectedValue == "varchar")
{
createdynamiccontrols_varchar();
}
//How to Proceed
}
protected void createdynamiccontrols_decimal()
{
int i = DropDownList5.SelectedIndex;
++i;
TableRow row;
row = new TableRow();
TableCell cell1;
cell1 = new TableCell();
//DropDownList2
DropDownList Range_DDL;
Range_DDL = new DropDownList();
Range_DDL.ID = "RandeDDL" + i.ToString();
Range_DDL.Items.Insert(0, new ListItem("--Select--", "--Select--"));
Range_DDL.Items.Insert(1, new ListItem("Equal", "Equal"));
Range_DDL.Items.Insert(2, new ListItem("NotEqual", "NotEqual"));
Range_DDL.Items.Insert(3, new ListItem("greater than", "greater than"));
Range_DDL.Items.Insert(2, new ListItem("lesser than", "lesser than"));
Range_DDL.Items.Insert(2, new ListItem("greater than or equal to", "greater than or equal to"));
Range_DDL.Items.Insert(2, new ListItem("lesser than or equal to", "lesser than or equal to"));
Range_DDL.Items.Insert(2, new ListItem("Contains", "Contains"));
Range_DDL.Items.Insert(2, new ListItem("Is Null", "Is Null"));
Range_DDL.Items.Insert(2, new ListItem("Is Not Null", "Is Not Null"));
Range_DDL.Items.Insert(2, new ListItem("Between", "Between"));
Range_DDL.AutoPostBack = true;
Range_DDL.SelectedIndexChanged += new System.EventHandler(Range_DDL_SelectedIndexChanged);
cell1.Controls.Add(Range_DDL);
//// Add the TableCell to the TableRow
row.Cells.Add(cell1);
dynamic_filter_table.Rows.Add(row);
dynamic_filter_table.EnableViewState = true;
ViewState["dynamic_filter_table"] = true;
}
//DropdownList2 to create dynamic text boxes
protected void Range_DDL_SelectedIndexChanged(object sender, EventArgs e)
{
int j = DropDownList5.SelectedIndex;
++j;
TableRow row;
row = new TableRow();
TableRow rowtwo;
rowtwo = new TableRow();
TableCell cell1;
cell1 = new TableCell();
TableCell cell2;
cell2 = new TableCell();
TableCell cell3;
cell3 = new TableCell();
TextBox tb1;
tb1 = new TextBox();
TextBox tb2;
tb2 = new TextBox();
Label lbl1;
lbl1 = new Label();
Label lbl2;
lbl2 = new Label();
//// Set a unique ID for each TextBox added
tb1.ID = "lowerbound_" + j.ToString();
tb2.ID = "upperbound_" + j.ToString();
lbl1.Text = "LowerBound:";
lbl1.Font.Size = FontUnit.Point(10);
lbl1.Font.Bold = true;
lbl1.Font.Name = "Arial";
lbl2.Text = "UpperBound:";
lbl2.Font.Size = FontUnit.Point(10);
lbl2.Font.Bold = true;
lbl2.Font.Name = "Arial";
Button addmore;
addmore = new Button();
addmore.ID = "Button" + j.ToString();
addmore.Text = "+";
addmore.Click += new System.EventHandler(addmore_click);
cell1.Controls.Add(lbl1);
cell2.Controls.Add(tb1);
cell2.Controls.Add(lbl2);
cell2.Controls.Add(tb2);
cell3.Controls.Add(addmore);
row.Cells.Add(cell1);
row.Cells.Add(cell2);
rowtwo.Cells.Add(cell3);
dynamic_filter_table.Rows.Add(row);
dynamic_filter_table.EnableViewState = true;
ViewState["dynamic_filter_table"] = true;
}
//Button Click to retrieve the input from dynamic generated text box and display in JQGrid.
protected void Button1_Click(object sender, EventArgs e)
{
int j = DropDownList5.SelectedIndex;
++j;
Panel6.Visible = true;
JQGrid9.Visible = true;
TextBox lowerboundd = dynamic_filter_table.FindControl("lowerbound_" + j.ToString()) as TextBox;
TextBox upperbound = dynamic_filter_table.FindControl("upperbound_" + j.ToString()) as TextBox;
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT a,b,c FROM TABLE WHERE " + DropDownList5.SelectedValue + " >= " + lowerboundd.Text + " AND " + DropDownList5.SelectedValue + " <= " + upperbound.Text, con);
**//Problems in retrieving the input of textboxes - Object Reference error**
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
Session["DataforSearch"] = ds.Tables[0];
}

You can find the source code and example on following link :
http://www.codeproject.com/Articles/20714/Dynamic-ASP-NET-control-creation-using-C
I also found this code online, I hope it would help you: You can modify this according to your needs in this code Button is added on the click of an another button.
Adding a new control to a form is really easy.
All you have to do is create a new instance of the control like any other class.
Eg:
Button NewButton = new button();
Then you fill out the properties of the control.
NewButton.Text = "My New Button";
After this setup an event handler.
NewButton.Click += new EventHandler(NewButton_Click);
Then in the button handler to tell which dynamic button was pressed you use the sender parameter.
void NewButton_Click(object sender, EventArgs e)
{
Button CurrentButton = (Button)sender;
CurrentButton.Text = "I was clicked";
}
Then finally the last step in setting the button up is to add the control to the form.
this.Controls.Add(NewButton);

Related

FindControl() returns null when searching for dynamic control

In my requirement I am creating dynamic controls by two events
Dropdownlist OnSelectedIndexChanged event
Onclick button event
In OnSelectedIndexChanged event i have created number of dynamic textbox.
Here I have create two dynamic textboxes.
I am getting all enquiry product list based on enquiry number from the dynamic textboxes on button click event
All are dynamic controls
While saving the productlist the checkbox control return null value
protected void ddlenqChaged(object sender, EventArgs e)
{
getenqTextbox();
}
protected void btnSearchClick(object sender, EventArgs e)
{
tblbill.Visible = true;
if (Convert.ToString(ViewState["Generated"]) != "true")
{
CreateDynamicControls();
ViewState["Generated"] = "true";
}
}
protected void getenqTextbox()
{
enqPanel.Controls.Clear();
if (Convert.ToInt32(ddlNoofEnq.SelectedValue) > 0)
{
for (int i = 1; i <= Convert.ToInt32(ddlNoofEnq.SelectedValue); i++)
{
TextBox _txtCode = new TextBox();
_txtCode.ID = "txtEnqqNo" + i;
_txtCode.Attributes.Add("ClientIDMode", "Static");
_txtCode.Width = 75;
_txtCode.CssClass = "AtCompleteByEnq";
enqPanel.Controls.Add(_txtCode);
}
}
}
protected void CreateDynamicControls()
{
int m = 1;
//int encount = click.buttonclick;
if (Convert.ToInt32(ddlNoofEnq.SelectedValue) > 0)
{
Table tbldynamic = new Table();
for (int k = 1; k <= Convert.ToInt32(ddlNoofEnq.SelectedValue); k++)
{
Panel1.Controls.Clear();
TextBox tb = (TextBox)enqPanel.FindControl("txtEnqqNo" + k);
if (tb != null)
{
if (!String.IsNullOrEmpty(tb.Text))
{
List<Enquiry_ProductListBLL> objlst = Enquiry_ProductListBLL.GetEnquiry_ProductListBLLs(tb.Text);
foreach (Enquiry_ProductListBLL item in objlst)
{
TableRow tr = new TableRow();
TableCell tc = new TableCell();
TableCell tc1 = new TableCell();
TableCell tc2 = new TableCell();
TableCell tc3 = new TableCell();
TableCell tc4 = new TableCell();
TableCell tc5 = new TableCell();
TableCell tc6 = new TableCell();
Master_ProductBLL objpdt = Master_ProductBLL.GetMaster_ProductBLL(item.ProductId);
CheckBox _chkRowNo = new CheckBox();
_chkRowNo.ID = "chkRowNo" + m;
_chkRowNo.Text = m.ToString();
_chkRowNo.Attributes.Add("ClientIDMode", "Static");
_chkRowNo.Attributes.Add("onclick", "getEnable(this);");
_chkRowNo.Checked = true;
TextBox _txtCode = new TextBox();
_txtCode.ID = "txtCodeRow" + m;
_txtCode.Attributes.Add("ClientIDMode", "Static");
_txtCode.Enabled = false;
_txtCode.Width = 75;
_txtCode.Attributes.Add("autocomplete", "off");
_txtCode.Text = objpdt.Code;
HiddenField _hdnPdtId = new HiddenField();
_hdnPdtId.ID = "hdnPdtId" + m;
_hdnPdtId.Value = item.ProductId.ToString();
HiddenField _hdEnqNo = new HiddenField();
_hdEnqNo.ID = "hdEnqNo" + m;
_hdEnqNo.Value = item.EnqNo;
_hdnPdtId.Value = item.ProductId.ToString();
TextBox _txtPdtName = new TextBox();
_txtPdtName.ID = "txtPdtNameRow" + m;
_txtPdtName.Attributes.Add("ClientIDMode", "Static");
_txtPdtName.Enabled = false;
_txtPdtName.Width = 150;
_txtPdtName.CssClass = "AtCompleteByName";
_txtPdtName.Text = objpdt.Name;
TextBox _txtQty = new TextBox();
_txtQty.ID = "txtQtyRow" + m;
_txtQty.Width = 80;
_txtQty.MaxLength = 8;
_txtQty.Attributes.Add("ClientIDMode", "Static");
//_txtQty.Attributes.Add("onblur", "GetTotal(this)");
//_txtQty.Enabled = false;
_txtQty.Text = item.Count.ToString();
DropDownList ddlUnits = new DropDownList();
ddlUnits.ID = "ddlUnits" + m;
ddlUnits.CssClass = "dropdowncss";
ddlUnits.Width = 100;
Bindings.BindUnitName(ddlUnits);
ddlUnits.Items.FindByText(item.PP).Selected = true;
tc.Controls.Add(_chkRowNo);
tc1.Controls.Add(_txtCode);
tc2.Controls.Add(_txtPdtName);
tc2.Controls.Add(_hdnPdtId);
tc2.Controls.Add(_hdEnqNo);
tc3.Controls.Add(_txtBrand);
tc4.Controls.Add(_txtThickness);
tc5.Controls.Add(ddlUnits);
tc6.Controls.Add(_txtQty);
tc.Attributes.Add("Width", "50px");
tr.Attributes.Add("id", "Rowid" + m);
tr.Attributes.Add("class", "paidRw");
tr.Cells.Add(tc);
tr.Cells.Add(tc1);
tr.Cells.Add(tc2);
tr.Cells.Add(tc3);
tr.Cells.Add(tc4);
tr.Cells.Add(tc5);
tr.Cells.Add(tc6);
tbldynamic.Rows.Add(tr);
m++;
}
}
}
}
Panel1.Controls.Add(tbldynamic);
}
}
Here I have override OnLoad event
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
CreateDynamicControls();
getenqTextbox();
}
My problem is i cannot find controls from Panel1
CheckBox chk = (CheckBox)Panel1.FindControl(chkId);
if (chk != null)
{
if (chk.Checked == true)
{
//my process
}
}
FindControl returns null value.
Here I have create dynamic controls two times.
I cannot have any problem with enquiry textbox, it was created first, but the second time button click event controls are return null.
FindControl does not walk the hierarchy.
See doc Control.FindControl()
This method will find a control only if the control is directly contained by the specified container; that is, the method does not search throughout a hierarchy of controls within controls.
Since your CheckBox is not a first-level child of the Panel, it cannot be retrieved this way. If you need a generic solution, I suggest to implement a recursive FindControl.

How to create text boxes and buttons dynamically and get the value from each text box in c#?

I'm trying to build tables dynamically with a text box and a button in each table. The tables are added successfully but when I pressed on the button it made a post back to the page and the tables were gone. So i build each table inside an updatePanel but when a button was clicked twice, a postback was occurred again.How can I prevent the potback? and then, how do I get the value inside the text boxes? TNX very much!
private void addTable(List<fileSaving> fs)
{
foreach (fileSaving f in fs){
UpdatePanel up = new UpdatePanel();
up.ID = "UpdatePanel-"+f.FileName;
up.UpdateMode = UpdatePanelUpdateMode.Conditional;
Table T = new Table();
T.CssClass = "filesTBL";
TableRow hTR = new TableRow();
TableCell td1 = new TableCell();
Image fileImg = new Image();
fileImg.ImageUrl = "images/"+f.FileExtension+".png";
td1.Controls.Add(fileImg);
hTR.Cells.Add(td1);
TableCell td2 = new TableCell();
td2.Text = f.ExpName;
hTR.Cells.Add(td2);
TableCell td3 = new TableCell();
Image expImg = new Image();
expImg.ImageUrl = "images/magnet.png";
td3.Controls.Add(expImg);
hTR.Cells.Add(td3);
T.Rows.Add(hTR);
TableRow mTR = new TableRow();
TableCell td4 = new TableCell();
td4.Text = "";
mTR.Cells.Add(td4);
TableCell td5 = new TableCell();
td5.Text = f.TeamID.ToString();
mTR.Cells.Add(td5);
TableCell td6 = new TableCell();
Image teamImg = new Image();
teamImg.ImageUrl = "images/team3.png";
td6.Controls.Add(teamImg);
mTR.Cells.Add(td6);
T.Rows.Add(mTR);
TableRow lTR = new TableRow();
TableCell td7 = new TableCell();
HyperLink downloadLink = new HyperLink();
downloadLink.Attributes.Add("href", "http://proj.ruppin.ac.il/igroup39/test2/tar5/tar5.zip");
downloadLink.ImageUrl = "images/download2.png";
downloadLink.ToolTip = "לחץ להורדה";
td7.Controls.Add(downloadLink);
lTR.Cells.Add(td7);
TableCell td8 = new TableCell();
if (f.ReportGrade != -1)
{
td8.Text = f.ReportGrade.ToString();
}
else
{
TextBox tb = new TextBox();
tb.ID = f.FileName + "-tb";
gFN = tb.ID;
tb.Width = 40;
td8.Controls.Add(tb);
Button btn = new Button();
btn.ID = f.FileName + "-btn";
btn.Text = "הזן ציון";
btn.Click += new EventHandler(btn_Click);
td8.Controls.Add(btn);
}
lTR.Cells.Add(td8);
TableCell td9 = new TableCell();
Image gradeImg = new Image();
gradeImg.ImageUrl = "images/grade.png";
td9.Controls.Add(gradeImg);
lTR.Cells.Add(td9);
T.Rows.Add(lTR);
up.ContentTemplateContainer.Controls.Add(T);
Page.Form.Controls.Add(up);
}
}
protected void btn_Click(object sender, EventArgs e)
{
if (!IsPostBack)
{
Button mybtn = (Button)sender;
Response.Write(mybtn.ID);
}
}
So after a long time thinking how to solved this, with help from some friend, I wrote this in page_load so when the button was pressed and postback occurred the page rebuild my dynamic controls, but only the button press- this is the role of the session.
My new code:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (Session["showFiles"] != null)
{
bool flag = (bool)Session["showFiles"];
if (flag == true)
{
fileSaving fs = new fileSaving();
List<fileSaving> fileslist = fs.filesList(hiddenLBL.Text);
addTable(fileslist);
}
}
}
ExpScheduleClass ESCC = new ExpScheduleClass();
List<string> labCourses = ESCC.getCourseList();
// dynamically create a dropdown list (aka DDL)
DDLCourses = new DropDownList();
DDLCourses.DataSource = labCourses; // set the data source
DDLCourses.DataBind(); // bind the data to the DDL control
DDLCourses.AutoPostBack = true;
DDLCourses.SelectedIndexChanged += DDLCourses_SelectedIndexChanged;
coursePH.Controls.Add(DDLCourses);
}
private void DDLCourses_SelectedIndexChanged(object sender, EventArgs e)
{
string[] coursesIDArr = DDLCourses.SelectedValue.Split(' ');
/* courseLBL.Text = coursesIDArr[0];
string courseID = coursesIDArr[0];//take the id from the list*/
courseLBL.Text = coursesIDArr[2];
classLBL.Text = coursesIDArr[4];
currnetYearLBL.Text = coursesIDArr[6];
semesterLBL.Text = coursesIDArr[8];
courseLBL.ForeColor = System.Drawing.Color.Black;
currnetYearLBL.ForeColor = System.Drawing.Color.Black;
semesterLBL.ForeColor = System.Drawing.Color.Black;
classLBL.ForeColor = System.Drawing.Color.Black;
ExpScheduleClass SIEGL = new ExpScheduleClass();
List<String> lessonsList = SIEGL.getLessonList(coursesIDArr[2]);
DDLLessons.DataSource = lessonsList; // set the data source
DDLLessons.DataBind();
}
protected void DDLLessons_SelectedIndexChanged(object sender, EventArgs e)
{
string[] lessonsIdArr = DDLLessons.SelectedValue.Split(' ');
string lessonID = lessonsIdArr[0];
lessonLBL.Text = lessonID;
dateLBL.Text = lessonsIdArr[1];
lessonLBL.ForeColor = System.Drawing.Color.Black;
hiddenLBL.Text = lessonID;
fileSaving fs = new fileSaving();
List<fileSaving> fileslist = fs.filesList(lessonID);
addTable(fileslist);
Session["showFiles"] = true;
}
private void addTable(List<fileSaving> fs)
{
foreach (fileSaving f in fs)
{
UpdatePanel up = new UpdatePanel();
up.ID = "UpdatePanel-" + f.FileName;
up.UpdateMode = UpdatePanelUpdateMode.Conditional;
Table T = new Table();
T.CssClass = "filesTBL";
//------------Header Row------------------------------------------------
TableRow hTR = new TableRow();
TableCell td1 = new TableCell();
Image fileImg = new Image();
fileImg.ImageUrl = "images/" + f.FileExtension + ".png";
td1.Controls.Add(fileImg);
hTR.Cells.Add(td1);
TableCell td2 = new TableCell();
td2.Text = f.ExpName;
hTR.Cells.Add(td2);
TableCell td3 = new TableCell();
Image expImg = new Image();
expImg.ImageUrl = "images/magnet.png";
td3.Controls.Add(expImg);
hTR.Cells.Add(td3);
T.Rows.Add(hTR);
//------------Middle Row------------------------------------------------
TableRow mTR = new TableRow();
TableCell td4 = new TableCell();
td4.Text = "";
mTR.Cells.Add(td4);
TableCell td5 = new TableCell();
td5.Text = f.TeamID.ToString();
mTR.Cells.Add(td5);
TableCell td6 = new TableCell();
Image teamImg = new Image();
teamImg.ImageUrl = "images/team3.png";
td6.Controls.Add(teamImg);
mTR.Cells.Add(td6);
T.Rows.Add(mTR);
//------------Last Row------------------------------------------------
TableRow lTR = new TableRow();
TableCell td7 = new TableCell();
HyperLink downloadLink = new HyperLink();
//downloadLink.Attributes.Add("href", "/igroup39/test2/project/reportFiles/" + f.FileName);
downloadLink.Attributes.Add("href", "http://proj.ruppin.ac.il/igroup39/test2/tar5/tar5.zip");
downloadLink.ImageUrl = "images/download2.png";
downloadLink.ToolTip = "לחץ להורדה";
td7.Controls.Add(downloadLink);
lTR.Cells.Add(td7);
TableCell td8 = new TableCell();
if (f.ReportGrade != -1)
{
td8.Text = f.ReportGrade.ToString();
}
else
{
TextBox tb = new TextBox();
tb.ID = f.FileName + "-tb";
gFN = tb.ID;
tb.Width = 40;
td8.Controls.Add(tb);
Button btn = new Button();
btn.ID = f.FileName + "-btn";
btn.Text = "הזן ציון";
btn.Click += new EventHandler(btn_Click);
td8.Controls.Add(btn);
}
lTR.Cells.Add(td8);
TableCell td9 = new TableCell();
Image gradeImg = new Image();
gradeImg.ImageUrl = "images/grade.png";
td9.Controls.Add(gradeImg);
lTR.Cells.Add(td9);
T.Rows.Add(lTR);
up.ContentTemplateContainer.Controls.Add(T);
Page.Form.Controls.Add(up);
//filesTablesPH.Controls.Add(up);
}
}
protected void btn_Click(object sender, EventArgs e)
{
Button mybtn = (Button)sender;
string btnID = mybtn.ID;
string[] file_Name = btnID.Split('-');
string tbID = file_Name[0] + "-tb";
string grade = ((TextBox)filesTablesPH.FindControl(tbID)).Text;
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert("+grade+")", true);
}

How to retain the dynamically generated web control inputs in viewstates for search functions

I am able to generate dynamic web controls based on DropDownlist selected input. I need to implement a button click event which should walk through all the inputs from those dynamic web controls and display the results in JQGrid Table.
Requirement: How to retain all the input texts from those dynamic web controls using SavedViewState() and LoadViewState(). I am new to dynamic web controls and Viewstates. Help needed
I have given my complete sample code.
My C# Code:
private void BindDropDownLists()
{
column_list_for_filter.ConnectionString = connection;
string item = "--Select--";
column_list_for_filter.SelectCommand = "SELECT DATA_TYPE + '_' + convert(varchar(10), ROW_NUMBER() OVER(ORDER BY DATA_TYPE))as DATA_TYPE, COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE (TABLE_NAME = 'RESULT' AND COLUMN_NAME IN ('Column1','Column2','Column3','Column4'))";
DropDownList5.DataTextField = "COLUMN_NAME";
DropDownList5.DataValueField = "DATA_TYPE";
DropDownList5.DataBind();
DropDownList5.Items.Insert(0, item);
}
protected void createdynamiccontrols_decimal()
{
int i = DropDownList5.SelectedIndex;
++i;
TableRow row = new TableRow();
row.ID = "TableRow_";
TableCell cell1 = new TableCell();
cell1.ID = "TableCell_";
DropDownList Range_DDL_Decimal = new DropDownList();
Range_DDL_Decimal.ID = "RandeDDL_Decimal" + i.ToString();
Range_DDL_Decimal.Items.Insert(0, new ListItem("--Select--", "--Select--"));
Range_DDL_Decimal.Items.Insert(1, new ListItem("Equal", "Equal"));
Range_DDL_Decimal.Items.Insert(2, new ListItem("NotEqual", "NotEqual"));
Range_DDL_Decimal.Items.Insert(3, new ListItem("greater than", "greater than"));
Range_DDL_Decimal.Items.Insert(4, new ListItem("lesser than", "lesser than"));
Range_DDL_Decimal.Items.Insert(5, new ListItem("greater than or equal to", "greater than or equal to"));
Range_DDL_Decimal.Items.Insert(6, new ListItem("lesser than or equal to", "lesser than or equal to"));
Range_DDL_Decimal.Items.Insert(7, new ListItem("Contains", "Contains"));
Range_DDL_Decimal.Items.Insert(8, new ListItem("Is Null", "Is Null"));
Range_DDL_Decimal.Items.Insert(9, new ListItem("Is Not Null", "Is Not Null"));
Range_DDL_Decimal.Items.Insert(10, new ListItem("Between", "Between"));
Range_DDL_Decimal.AutoPostBack = true;
Range_DDL_Decimal.SelectedIndexChanged += new System.EventHandler(Range_DDL_Decimal_SelectedIndexChanged);
cell1.Controls.Add(Range_DDL_Decimal);
//// Add the TableCell to the TableRow
row.Cells.Add(cell1);
dynamic_filter_table.Rows.Add(row);
dynamic_filter_table.EnableViewState = true;
ViewState["dynamic_filter_table"] = true;
}
protected void Range_DDL_Decimal_SelectedIndexChanged(object sender, EventArgs e)
{
int j = DropDownList5.SelectedIndex;
++j;
TableCell cell2 = new TableCell();
TextBox tb1 = new TextBox();
TextBox tb2 = new TextBox();
Label lbl1 = new Label();
Label lbl2 = new Label();
// Set a unique ID for each TextBox added
tb1.ID = "lowerbound_" + j.ToString();
tb2.ID = "upperbound_" + j.ToString();
lbl1.Text = "LowerBound:";
lbl1.Font.Size = FontUnit.Point(10);
lbl1.Font.Bold = true;
lbl1.Font.Name = "Arial";
lbl2.Text = "UpperBound:";
lbl2.Font.Size = FontUnit.Point(10);
lbl2.Font.Bold = true;
lbl2.Font.Name = "Arial";
cell2.Controls.Add(lbl1);
cell2.Controls.Add(tb1);
cell2.Controls.Add(lbl2);
cell2.Controls.Add(tb2);
TableRow rowtwo = dynamic_filter_table.FindControl("TableRow_") as TableRow;
rowtwo.Cells.Add(cell2);
dynamic_filter_table.Rows.Add(rowtwo);
dynamic_filter_table.EnableViewState = true;
ViewState["dynamic_filter_table"] = true;
}
protected override object SaveViewState()
{
/***1. Retain DDL 1 selected text
2. Retain DDL 2 selected text DDL2 generated by DDL 1
3. Retain Tb1.text and tb2.text generated by DDL2 ***/
//How to Proceed
}
protected override void LoadViewState(object savedState)
{
//How to Proceed
}
protected void Button1_Click(object sender, EventArgs e)
{
int j = DropDownList5.SelectedIndex;
++j;
Panel6.Visible = true;
JQGrid9.Visible = true;
//Find Control not working
TextBox lowerboundd = dynamic_filter_table.FindControl("lowerbound_" + j.ToString()) as TextBox;
TextBox upperbound = dynamic_filter_table.FindControl("upperbound_" + j.ToString()) as TextBox;
con.Open();
// **How to pass values to this query from savedstate**
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM RESULT WHERE " + DropDownList5.Text + DDL2.Text + " >= " + lowerboundd.Text + " AND " + DropDownList5.Text + " <= " + upperbound.Text, con);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
Session["DataforSearch"] = ds.Tables[0];
}
protected void Page_Load(object sender, EventArgs e)
{
Panel6.Visible = false;
JQGrid9.Visible = false;
if (Session["DataforSearch"] != null)
{
Panel6.Visible = true;
JQGrid9.Visible = true;
JQGrid9.DataSource = Session["DataforSearch"] as string;
}
if (!IsPostBack)
{
BindDropDownLists();
}
else
{
if (!String.IsNullOrEmpty(DropDownList5.SelectedValue))
{
if (DropDownList5.SelectedValue.Contains("decimal"))
{
createdynamiccontrols_decimal();
}
else if (DropDownList5.SelectedValue.Contains("varchar"))
{
createdynamiccontrols_varchar();
}
else if (DropDownList5.SelectedValue.Contains("datetime"))
{
createdynamiccontrols_datetime();
}
else if (DropDownList5.SelectedValue.Contains("int"))
{
createdynamiccontrols_int();
}
}
}
}
protected void Page_PreInit(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDownLists();
}
else
{
if (!String.IsNullOrEmpty(DropDownList5.SelectedValue))
{
if (DropDownList5.SelectedValue.Contains("decimal"))
{
createdynamiccontrols_decimal();
}
else if (DropDownList5.SelectedValue.Contains("varchar"))
{
createdynamiccontrols_varchar();
}
else if (DropDownList5.SelectedValue.Contains("datetime"))
{
createdynamiccontrols_datetime();
}
else if (DropDownList5.SelectedValue.Contains("int"))
{
createdynamiccontrols_int();
}
}
}
You don't need to override SaveViewState/LoadViewState. But you have to keep selections in ViewState to create controls on postback. This should work:
internal enum DataType
{
None = 0,
Decimal
}
internal enum Operator
{
Equal,
GreaterThan,
None
}
public partial class _Default : Page
{
private DataType DataType
{
get
{
object dataType = ViewState["DataType"];
if (dataType != null) return (DataType)dataType;
return DataType.None;
}
set { ViewState["DataType"] = value; }
}
private int? DataTypeIndex
{
get { return ViewState["DataTypeIndex"] as int?; }
set { ViewState["DataTypeIndex"] = value; }
}
private Operator Operator
{
get
{
var #operator = ViewState["Operator"];
if (#operator != null)
return (Operator)#operator;
return Operator.None;
}
set { ViewState["Operator"] = value; }
}
private void BindDropDownLists()
{
column_list_for_filter.ConnectionString = connection;
string item = "--Select--";
column_list_for_filter.SelectCommand = "SELECT DATA_TYPE + '_' + convert(varchar(10), ROW_NUMBER() OVER(ORDER BY DATA_TYPE))as DATA_TYPE, COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE (TABLE_NAME = 'RESULT' AND COLUMN_NAME IN ('Column1','Column2','Column3','Column4'))";
DropDownList5.DataTextField = "COLUMN_NAME";
DropDownList5.DataValueField = "DATA_TYPE";
DropDownList5.DataBind();
DropDownList5.Items.Insert(0, item);
}
protected void DropDownList5_SelectedIndexChanged(object sender, EventArgs e)
{
DataTypeIndex = DropDownList5.SelectedIndex;
if (DropDownList5.SelectedValue.Contains("decimal"))
{
DataType = DataType.Decimal;
}
CreateDataTypeControl();
//else if (DropDownList5.SelectedValue.Contains("varchar"))
//{
//DataType = DataType.Varchar;
//}
//else if (DropDownList5.SelectedValue.Contains("datetime"))
//{
//DataType = DataType.DateTime;
//}
//else if (DropDownList5.SelectedValue.Contains("int"))
//{
//DataType = DataType.Integer;
//}
}
protected void Range_DDL_Decimal_SelectedIndexChanged(object sender, EventArgs e)
{
var ddl = (DropDownList)sender;
switch (ddl.SelectedIndex)
{
case 1:
Operator = WebApplication1.Operator.Equal;
break;
}
CreateRangeControls();
}
protected void createdynamiccontrols_decimal()
{
int i = DataTypeIndex.GetValueOrDefault();
++i;
TableRow row = new TableRow();
row.ID = "TableRow_";
TableCell cell1 = new TableCell();
cell1.ID = "TableCell_";
DropDownList Range_DDL_Decimal = new DropDownList();
Range_DDL_Decimal.ID = "RandeDDL_Decimal" + i.ToString();
Range_DDL_Decimal.Items.Insert(0, new ListItem("--Select--", "--Select--"));
Range_DDL_Decimal.Items.Insert(1, new ListItem("Equal", "Equal"));
Range_DDL_Decimal.Items.Insert(2, new ListItem("NotEqual", "NotEqual"));
Range_DDL_Decimal.Items.Insert(3, new ListItem("greater than", "greater than"));
Range_DDL_Decimal.Items.Insert(4, new ListItem("lesser than", "lesser than"));
Range_DDL_Decimal.Items.Insert(5, new ListItem("greater than or equal to", "greater than or equal to"));
Range_DDL_Decimal.Items.Insert(6, new ListItem("lesser than or equal to", "lesser than or equal to"));
Range_DDL_Decimal.Items.Insert(7, new ListItem("Contains", "Contains"));
Range_DDL_Decimal.Items.Insert(8, new ListItem("Is Null", "Is Null"));
Range_DDL_Decimal.Items.Insert(9, new ListItem("Is Not Null", "Is Not Null"));
Range_DDL_Decimal.Items.Insert(10, new ListItem("Between", "Between"));
Range_DDL_Decimal.SelectedIndexChanged += new System.EventHandler(Range_DDL_Decimal_SelectedIndexChanged);
Range_DDL_Decimal.AutoPostBack = true;
cell1.Controls.Add(Range_DDL_Decimal);
//// Add the TableCell to the TableRow
row.Cells.Add(cell1);
dynamic_filter_table.Rows.Add(row);
dynamic_filter_table.EnableViewState = true;
ViewState["dynamic_filter_table"] = true;
}
protected void CreateRangeTextBoxes()
{
int j = DataTypeIndex.GetValueOrDefault();
++j;
TableCell cell2 = new TableCell();
cell2.ID = "Range";
TextBox tb1 = new TextBox();
TextBox tb2 = new TextBox();
Label lbl1 = new Label();
Label lbl2 = new Label();
// Set a unique ID for each TextBox added
tb1.ID = "lowerbound_" + j.ToString();
tb2.ID = "upperbound_" + j.ToString();
lbl1.Text = "LowerBound:";
lbl1.Font.Size = FontUnit.Point(10);
lbl1.Font.Bold = true;
lbl1.Font.Name = "Arial";
lbl2.Text = "UpperBound:";
lbl2.Font.Size = FontUnit.Point(10);
lbl2.Font.Bold = true;
lbl2.Font.Name = "Arial";
cell2.Controls.Add(lbl1);
cell2.Controls.Add(tb1);
cell2.Controls.Add(lbl2);
cell2.Controls.Add(tb2);
TableRow rowtwo = dynamic_filter_table.FindControl("TableRow_") as TableRow;
rowtwo.Cells.Add(cell2);
dynamic_filter_table.Rows.Add(rowtwo);
dynamic_filter_table.EnableViewState = true;
ViewState["dynamic_filter_table"] = true;
}
protected void Button1_Click(object sender, EventArgs e)
{
int j = DropDownList5.SelectedIndex;
++j;
Panel6.Visible = true;
JQGrid9.Visible = true;
Find Control not working
TextBox lowerboundd = dynamic_filter_table.FindControl("lowerbound_" + j.ToString()) as TextBox;
TextBox upperbound = dynamic_filter_table.FindControl("upperbound_" + j.ToString()) as TextBox;
DropDownList range = dynamic_filter_table.FindControl("RandeDDL_Decimal" + j.ToString()) as DropDownList;
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM RESULT WHERE " + DropDownList5.Text + DDL2.Text + " >= " + lowerboundd.Text + " AND " + DropDownList5.Text + " <= " + upperbound.Text, con);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
Session["DataforSearch"] = ds.Tables[0];
}
protected void Page_Load(object sender, EventArgs e)
{
Panel6.Visible = false;
JQGrid9.Visible = false;
if (Session["DataforSearch"] != null)
{
Panel6.Visible = true;
JQGrid9.Visible = true;
JQGrid9.DataSource = Session["DataforSearch"] as string;
}
CreateDataTypeControl();
CreateRangeControls();
}
void CreateDataTypeControl()
{
switch (DataType)
{
case DataType.Decimal:
createdynamiccontrols_decimal();
break;
}
}
void CreateRangeControls()
{
switch (Operator)
{
case WebApplication1.Operator.GreaterThan:
case Operator.Equal:
CreateRangeTextBoxes();
break;
}
}
}

add text box dynamically and capture data on button click

I am adding text boxes dynamically and trying to capture data entered in text box on button click. but what is happening is , though I entered the data in the text box, when I clicked the button, the page is getting loaded and the control is getting created again. As a result , I am loosing the data in the text box. Can you tell me how can I capture this data entered to the dynamically created text boxes.
My sample code is as follows:
protected void Page_Load(object sender, EventArgs e)
{
Table tblTextboxes = new Table();
for(int i=0;i<10;i++)
{
TableRow tr=new TableRow();
TableCell tc=new TableCell();
TextBox tb=new TextBox();
tb.ID=i.ToString();
tc.Controls.Add(tb);
tr.Cells.Add(tc);
TableCell tc1=new TableCell();
LinkButton lnk=new LinkButton();
lnk.ID=i.ToString()+tb.Text+"lnk";
lnk.Text = "Show";
lnk.Click+=new EventHandler(lnk_Click);
tc1.Controls.Add(lnk);
tr.Cells.Add(tc1);
tblTextboxes.Rows.Add(tr);
}
placeTest.Controls.Add(tblTextboxes);
}
void lnk_Click(object sender, EventArgs e)
{
LinkButton lnk=sender as LinkButton;
Label lbl=new Label();
lbl.Text="The text is"+lnk.ID;
placeTest.Controls.Add(lbl);
}
LinkButton ID is changed every time you enter text into TextBox and post back.
One thing you want to make sure when creating control dynamically is - you want to recreate them with same ID when post back.
Updated Solution (to retrieve text from TextBox)
protected void Page_Load(object sender, EventArgs e)
{
var tblTextboxes = new Table();
for (int i = 0; i < 10; i++)
{
var tr = new TableRow();
var tc = new TableCell();
var tb = new TextBox {ID = i.ToString()};
tc.Controls.Add(tb);
tr.Cells.Add(tc);
var tc1 = new TableCell();
// This is a fix for - lnk.ID=i.ToString()+tb.Text+"lnk";
var lnk = new LinkButton {ID = i + "lnk", Text = "Show"};
lnk.Click += lnk_Click;
tc1.Controls.Add(lnk);
tr.Cells.Add(tc1);
tblTextboxes.Rows.Add(tr);
}
placeTest.Controls.Add(tblTextboxes);
}
void lnk_Click(object sender, EventArgs e)
{
var lnk = sender as LinkButton;
var lbl = new Label();
lbl.Text = "LinkButton ID: " + lnk.ID;
// Get number value from string
string id = Regex.Replace(lnk.ID, #"[^\d]", "");
// Retrieves a TextBox control by ID
var control = FindControlRecursive(Page, id);
if (control != null)
{
var textbox = control as TextBox;
lbl.Text += "; TextBox Text: " + textbox.Text;
}
placeTest.Controls.Add(lbl);
}
public Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
return root;
return root.Controls.Cast<Control>()
.Select(c => FindControlRecursive(c, id))
.FirstOrDefault(c => c != null);
}
Based on the MSDN, I would recommend to use Page class's Init event. Look in to the title View State and Dynamically Added Controls for explanation. Also, I would recommend to add dynamic controls at the end of all existing controls. Create table first, and then add the text boxes.
I modified your code. It worked for me. I used VS 2012, .Net 4.5
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(DateTime.Now.ToString());
}
protected void Page_Init(object sender, EventArgs e)
{
Table tblTextboxes = new Table();
for (int i = 0; i < 10; i++)
{
TableRow tr = new TableRow();
TableCell tc = new TableCell();
TextBox tb = new TextBox();
tb.ID = i.ToString();
tc.Controls.Add(tb);
tr.Cells.Add(tc);
//TableCell tc1 = new TableCell();
//LinkButton lnk = new LinkButton();
//lnk.ID = i.ToString() + tb.Text + "lnk";
//lnk.Text = "Show";
//lnk.Click += new EventHandler(lnk_Click);
//tc1.Controls.Add(lnk);
//tr.Cells.Add(tc1);
tblTextboxes.Rows.Add(tr);
}
placeTest.Controls.Add(tblTextboxes);
}
protected void Button1_Click(object sender, EventArgs e)
{
}

Cant fire dropDownList selectionChange event from Backend

I'm not able to fire the method on Selection-change. I'm adding the DropDownList itself from code behind. Code :
private TableCell CreateMTPLTypeCell(int insurerId, string MTPLType)
{
TableCell rg = new TableCell();
rg.ID = string.Concat("rg_", insurerId);
rg.CssClass = "formItem";
//if (insurerId == 14)
//{
DropDownList ddl = new DropDownList();
ddl.ID = "MTPLTypes";
ddl.Items.Add(new ListItem("Standard", "1")); // add list items
ddl.Items.Add(new ListItem("DubultOCTA", "2"));
ddl.Items.Add(new ListItem("DubultOCTA+vējst", "3"));
//ddl.SelectedIndex =
// ddl.Items.IndexOf(ddl.Items.
// FindByValue(MTPLType));
ddl.SelectedIndexChanged += new EventHandler(MTPLType_selectedIndexChange);
ddl.AutoPostBack = true;
rg.Controls.Add(ddl);
//}
return rg;
}
void MTPLType_selectedIndexChange(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
int insurerId = Int32.Parse(ddl.ID.Replace("rg_", ""));
MTPLQuotes quotes = proposal.Properties.MtplQuotes[insurerId];
if (quotes == null) return;
proposal.GetSingleMTPLQuote(insurerId, Helpers.PortalUtilities.CurrentUser, BrokerInfo.GetBrokerInfo().Country.ID);
DrawMtplQuotes(mtplPaymentMappingsCount > 0);
}
Do I miss some extra parameters on DropDownList object ?
Atm it works like that: After selectionChange it starts "loading" but it dosnt reach to the method. :/
In same class i have antoher tableCell with onChange event (Text_Change) -> this works ok.
private TableCell CreateInsurerMtplDiscountCell(int insurerId, decimal discount)
{
TableCell c = new TableCell();
c.CssClass = "formItem";
c.Style[HtmlTextWriterStyle.PaddingLeft] = "25px";
TextBox txt = new TextBox();
txt.ID = string.Format("ins_disc_{0}", insurerId);
txt.Text = discount > 0 ? discount.ToString() : "";
txt.TextChanged += new EventHandler(insurerDiscountPercent_TextChanged);
txt.AutoPostBack = true;
txt.Width = new Unit(40);
c.Controls.Add(txt);
Literal l = new Literal();
l.Text = "%";
c.Controls.Add(l);
return c;
}
void insurerDiscountPercent_TextChanged(object sender, EventArgs e)
{
TextBox txt = (TextBox)sender;
int insurerId = Int32.Parse(txt.ID.Replace("ins_disc_", ""));
MTPLQuotes quotes = proposal.Properties.MtplQuotes[insurerId];
if (quotes == null) return;
decimal discountPercent;
if (!Decimal.TryParse(txt.Text, out discountPercent))
discountPercent = 0;
quotes.InsurerDiscountPercent = discountPercent;
foreach (MTPLQuote quote in quotes.Quotes)
ApplyMtplInsurerDiscount(quote, discountPercent);
DrawMtplQuotes(mtplPaymentMappingsCount > 0);
}
Got it fixed - The problem was about TableCell.ID (rg.ID = string.Concat("rg_", insurerId);) . After removing it everything worked fine. Anyone know why is that so ?
I think you have to refresh your Website after creating a new control.
i would suggesst you to use AJAX-updatepanels (so you dont have to refresh the whole site).
to add the OnChanged-Event Name you should also be able to add a string Name instead of the eventhandler itselfe.
ddl.SelectedIndexChanged = "MTPLType_selectedIndexChange";
I think you have to use "protected void" instead of "private void" its not reachable for the control cause of the permission restriction.
You should be binding your SelectedIndexChanged event to the dropdown list on the Page_PreInit event.
Then it should work.

Categories

Resources