I have a web page with multiple Drop Down list created at run time using Template fiels in GridView.
I have assigned event handler to DDL on selectedindexchange event.
But this event handler function is getting called only once and my gridview is getting updated only once.
How do I make my event handler function be called after every selection index change.
Here is MY Code
foreach (DataColumn coloumn in dt.Columns)
{
if (!coloumn.ColumnName.Equals("empName"))
{
var linkF = new TemplateField();
linkF.HeaderText = coloumn.ColumnName;
linkF.HeaderTemplate = new LinkColumn(ListItemType.Header, coloumn.ColumnName,folder);
linkF.ItemTemplate = new LinkColumn(ListItemType.Item, coloumn.ColumnName,folder);
GridView1.Columns.Insert(y, linkF);
y++;
}
else if (coloumn.ColumnName.Equals("empName"))
{
//Response.Write("Came");
BoundField bfield = new BoundField();
////Initalize the DataField value.
bfield.DataField = coloumn.ColumnName;
////Initialize the HeaderText field value.
bfield.HeaderText = coloumn.ColumnName;
GridView1.Columns.Insert(y, bfield);
y++;
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
class LinkColumn : DetailView, ITemplate
{
int id;
ListItemType _item;
String colN = null;
String fold;
public LinkColumn(ListItemType item, String colNa,String f)
{
_item = item;
colN = colNa;
fold = f;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (_item)
{
case ListItemType.Header:
DetailView.dp = new DropDownList();
Label lb = new Label();
MySqlCommand cm = new MySqlCommand("select distinct " + colN + " from " + fold + "",conn);
MySqlDataAdapter ad = new MySqlDataAdapter();
DataTable d = new DataTable();
ad.SelectCommand = cm;
ad.Fill(d);
DetailView.dp.DataTextField = colN;
DetailView.dp.DataValueField = colN;
DetailView.dp.DataSource = d;
DetailView.dp.DataBind();
lb.Text = colN.ToUpperInvariant();
dp.AutoPostBack = true;
container.Controls.Add(lb);
container.Controls.Add(DetailView.dp);
DetailView.dp.SelectedIndexChanged += new EventHandler(dp_Selected);
break;
case ListItemType.Item:
TextBox tb1 = new TextBox();
tb1.Enabled = false;
tb1.DataBinding += new EventHandler(tb1_Data);
tb1.Columns = 30;
container.Controls.Add(tb1);
break;
}
}
void tb1_Data(object sender, EventArgs e)
{
TextBox txt = (TextBox)sender;
GridViewRow cont = (GridViewRow)txt.NamingContainer;
object dataV = DataBinder.Eval(cont.DataItem, colN);
if (dataV != DBNull.Value)
{
txt.Text = dataV.ToString();
}
}
void dp_Selected(object sender, EventArgs e)
{
DropDownList list = (DropDownList)sender;
String name = list.SelectedValue;
Session["cols"] = name;
DetailView.colName = Session["cols"].ToString();
DetailView.flag = true;
}
Mu Event Handler function dp_selected is called only Once. I have called my GridBind() function in Page_Load().
Any help would be highly appreciated.
Thanks in Advance
Related
i'm new to c# programming, I had coded in c#(winforms) to get the output as: if an Item in the list box is clicked then the items should be displayed in the text box ,i had coded but its little bit hectic to implement to go further.
public partial class Form1 : Form
{
TextBox[] tb = new TextBox[5];
TextBox[] t = new TextBox[5];
TextBox[] t1 = new TextBox[5];
int[] tblist = new int[5];
public Form1()
{
InitializeComponent();
tb[0] = new TextBox();
tb[1] = new TextBox();
tb[2] = new TextBox();
tb[3] = new TextBox();
tb[4] = new TextBox();
t[0] = new TextBox();
t[1] = new TextBox();
t[2] = new TextBox();
t[3] = new TextBox();
t[4] = new TextBox();
t1[0] = new TextBox();
t1[1] = new TextBox();
t1[2] = new TextBox();
t1[3] = new TextBox();
t1[4] = new TextBox();
} //how can I simplify this by not assigning new to every textbox that i had created
// this button click is used to save items in the textbox in the listbox selected item
here how can we minimize the code : listbox selected index differs but the functions remains the same..
private void button1_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex == 0)
{
tb[0].Text = textBox1.Text;
tb[1].Text = textBox2.Text;
tb[2].Text = textBox3.Text;
tb[3].Text = textBox4.Text;
tb[4].Text = textBox5.Text;
}
if (listBox1.SelectedIndex == 1)
{
t[0].Text = textBox1.Text;
t[1].Text = textBox2.Text;
t[2].Text = textBox3.Text;
t[3].Text = textBox4.Text;
t[4].Text = textBox5.Text;
}
if (listBox1.SelectedIndex == 2)
{
t1[0].Text = textBox1.Text;
t1[1].Text = textBox2.Text;
t1[2].Text = textBox3.Text;
t1[3].Text = textBox4.Text;
t1[4].Text = textBox5.Text;
}
}
//here an item is clicked in the list box., so then items in the text box can be store in the listbox selected index
private void listBox1_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex == 0)
{
textBox1.Text = tb[0].Text;
textBox2.Text = tb[1].Text;
textBox3.Text = tb[2].Text;
textBox4.Text = tb[3].Text;
textBox5.Text = tb[4].Text;
}
if (listBox1.SelectedIndex == 1)
{ textBox1.Text = t[0].Text;
textBox2.Text = t[1].Text;
textBox3.Text = t[2].Text;
textBox4.Text = t[3].Text;
textBox5.Text = t[4].Text;
}
if (listBox1.SelectedIndex == 2)
{
textBox1.Text = t1[0].Text;
textBox2.Text = t1[1].Text;
textBox3.Text = t1[2].Text;
textBox4.Text = t1[3].Text;
textBox5.Text = t1[4].Text;
}
`
You may use a for loop for your arrays.
for(var i = 0; i < tb.Length; i++)
{
tb[i] = new TextBox();
t[i] = new TextBox();
t1[i] = new TextBox();
}
This is a snippet from code that I use.
Load your values into DataTables
and add a tableLayoutPanel to the form where you want the textboxes to go.
Call SetTextboxes function with datatable (or you can send your list here, just change the parameters and loop a little.
This will dynamically add textboxes to your form very quickly.
class SurroundingClass
{
private void SetTextboxes(datatable DT)
{
//Clear the previous textboxes
pnlLayoutExpenses.Controls.clear();
//loop through table and create new textboxes
foreach (DataRow row in DT.Rows)
formAddTextbox(row("dataTableColumnWhichHoldsTextboxText"));
}
private void formAddTextbox(string fieldname)
{
Integer elementCount = 0;
TextBox txtYourField = new TextBox();
txtYourField.Width = 100;
txtYourField.Height = 20;
//txtYourField.ReadOnly = true;
txtYourField.Text = fieldname;
txtYourField.tag = elementCount;
// Use tableLayoutPanel
pnlLayoutExpenses.SetCellPosition(txtType, new TableLayoutPanelCellPosition(0, elementCount));
pnlLayoutExpenses.Controls.Add(txtType);
}
}
I am new to windows application.I have a table in which there are two fields namely,Title and Type.
In Type field i have two values "O" & "T".
Now i have to populate a datagrid with this table Title as first column and in second column depending on the Type field value i have to place a control i.e when Type field will have "O" at that time i have to place a combobox in that column and when it is "T" i have to place a text Box
i have tried a lot and googled a lot but both controls in same column is quite difficult for me as a beginner.
Plz help me with this requirement.
this is my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ERP_Ship.App_Code.Fleet_Person;
using ERP_Ship.App_Code.Appraisal;
using ERP_Ship.Forms.Master;
using ERP_Ship.App_Code.Common;
using ERP_Ship.App_Code.Vessel_Hardening_Measures;
namespace ERP_Ship.Forms.Reports
{
public partial class Vessel_Hardening_Measures : Form
{
// ? //
private DataSet ds = new DataSet("myDs");
private DataTable dt = new DataTable("Apprdtl");
//Define controls must be add to data grid.
private Label lblControl = new Label();
private TextBox txtControl = new TextBox();
private ComboBox cboControl = new ComboBox();
//Capture the clicked cell
private DataGrid.HitTestInfo hitTestGrid;
//Control definishion to add to DataGrid
DataGridTableStyle dataGridStyle = new DataGridTableStyle();
DataGridTextBoxColumn dataGridLableTitle = new DataGridTextBoxColumn();
DataGridTextBoxColumn dataGridLableTitle1 = new DataGridTextBoxColumn();
DataGridTextBoxColumn dataGridLableTitle2 = new DataGridTextBoxColumn();
//DataGridTextBoxColumn dataGridLable = new DataGridTextBoxColumn();
DataGridTextBoxColumn dataGridTextBox = new DataGridTextBoxColumn();
DataGridTextBoxColumn dataGridComboBox = new DataGridTextBoxColumn();
private System.Windows.Forms.DataGrid gv_Appraisal;
#region Form Level Variables
string _strName;
string _strCDCNo;
//DataTable dt = new DataTable();
// OracleConnection con1 = new OracleConnection(ConfigurationManager.ConnectionStrings["MySQLConnection"].ConnectionString.ToString());
I_Common objCommon = new I_Common();
DataTable dt1 = new DataTable("dt1");
#endregion
#region Public Properties
public string SearchName
{
set
{
_strName = value;
}
get
{
return _strName;
}
}
public string SearchCDCNo
{
set
{
_strCDCNo = value;
}
get
{
return _strCDCNo;
}
}
#endregion
public Vessel_Hardening_Measures()
{
InitializeComponent();
InitializeControls();
Load_Year();
//for (int index = 0; index <= gv_Appraisal.Columns.Count - 1; index++)
//{
// gv_Appraisal.Columns[index].DataPropertyName = gv_Appraisal.Columns[index].Name;
//}
//gv_Appraisal.AutoGenerateColumns = false;
}
private void InitializeControls()
{
//label property
lblControl.Cursor = Cursors.Hand;
lblControl.ForeColor = Color.Red;
lblControl.Font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic);
//textbox property
txtControl.Cursor = Cursors.Hand;
txtControl.BackColor = Color.WhiteSmoke;
txtControl.ForeColor = Color.DarkSlateBlue;
txtControl.Font = new Font("Arial", 8, FontStyle.Bold);
//textbox events.
txtControl.TextChanged += new EventHandler(txtTextChanged);
string[] dropdownitems = { "Yes", "No", "Not Applicable" };
//Define and add ComboBox rows, will be added to data grid.
for (int i = 0; i < dropdownitems.Count(); i++)
cboControl.Items.Add(dropdownitems[i]);
//combobox property
cboControl.Cursor = Cursors.Hand;
cboControl.DropDownStyle = ComboBoxStyle.DropDownList;
//combobox events.
cboControl.SelectedIndexChanged += new EventHandler(cboSelectedIndexChanged);
}
private void DesignTableStyle()
{
dataGridStyle.PreferredRowHeight = 24;
dataGridStyle.MappingName = "Apprdtl";
gv_Appraisal.TableStyles.Add(dataGridStyle);
dataGridStyle.GridColumnStyles.Add(dataGridLableTitle);
dataGridStyle.GridColumnStyles.Add(dataGridLableTitle1);
dataGridStyle.GridColumnStyles.Add(dataGridLableTitle2);
dataGridStyle.GridColumnStyles.Add(dataGridTextBox);
//dataGridStyle.GridColumnStyles.Add(dataGridComboBox);
dataGridLableTitle.HeaderText = "vhm_id";
dataGridLableTitle.MappingName = "vhm_id";
dataGridLableTitle.Width = 1;
//dataGridLableTitle.Width = 40;
dataGridLableTitle1.HeaderText = "Title";
dataGridLableTitle1.MappingName = "Title";
dataGridLableTitle1.Width = 150;
dataGridLableTitle2.HeaderText = "Type";
dataGridLableTitle2.MappingName = "Type";
dataGridLableTitle2.Width = 1;
//dataGridLableTitle2.Width = 40;
dataGridTextBox.HeaderText = "TEXTBOX_COL";
dataGridTextBox.MappingName = "TextBox_Col";
dataGridTextBox.Width = 130;
//dataGridComboBox.HeaderText = "COMBOBOX_COL";
//dataGridComboBox.MappingName = "ComboBox_col";
//dataGridComboBox.Width = 130;
}
private void Load_DNF() // DATA NOT FOUND OF CDC NO
{
try
{
using (BL_Vessel_Hardening_Measures obj_vsl_hardening_measures = new BL_Vessel_Hardening_Measures())
{
DataTable dataTable = new DataTable();
ds = obj_vsl_hardening_measures.Get_Vessel_Hardening_Measures();
dt1 = ds.Tables[0];
DataColumn dc = new DataColumn("vhm_id");
//Add created column to datatable object.
dt.Columns.Add(dc);
//Create a new column for datatable.
dc = new DataColumn("Title");
//Add created column to datatable object.
dt.Columns.Add(dc);
//Create a new column for datatable.
dc = new DataColumn("Type");
//Add created column to datatable object.
dt.Columns.Add(dc);
//Create a new column for datatable.
//Create a new column for datatable.
dc = new DataColumn("TextBox_Col", System.Type.GetType("System.String"));
//Add created column to datatable object.
dt.Columns.Add(dc);
DataRow dr;
for (int i = 0; i < dt1.Rows.Count; i++)
{
dr = dt.NewRow();
dr["vhm_id"] = dt1.Rows[i]["vhm_id"];
dr["Title"] = dt1.Rows[i]["Title"];
dr["Type"] = dt1.Rows[i]["Type"];
dr["TextBox_Col"] = "";
//dr["ComboBox_Col"] = "";
dt.Rows.Add(dr);
}
// gv_Appraisal.DataSource = ds.Tables[0];
gv_Appraisal.DataSource = dt;
ds.Tables.Remove("Apprdtl");
ds.Tables.Add(dt);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btn_Close_Click(object sender, EventArgs e)
{
cls_Utility.Close_Pending_Form();
Home objHome = new Home();
I_Common.CloseForm(this.MdiParent, this, objHome);
}
private void Reset_Controls()
{
//txt_CDC_NO.Text = "";
//cmb_Name.SelectedIndex = -1;
}
~Vessel_Hardening_Measures()
{
this.Close();
}
private void Vessel_Hardening_Measures_FormClosed(object sender, FormClosedEventArgs e)
{
cls_Utility.Close_Pending_Form();
}
private void Load_Year()
{
try
{
//ddl_Year.DisplayMember = "Year";
//ddl_Year.ValueMember = "Year";
objCommon.Load_Years(ddl_Year, 1);
//string str_year = "";
//str_year = DateTime.Now.AddYears(-1).Year.ToString();
//ddl_Year.Items.Add(str_year);
//str_year = DateTime.Now.Year.ToString();
//ddl_Year.Items.Add(str_year);
// ddl_Year.SelectedIndex = 1;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Alert", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Vessel_Hardening_Measures_Load(object sender, EventArgs e)
{
DesignTableStyle();
Load_DNF();
ERP_Ship.App_Code.Common.I_Common.MdiFormTopPanel("Vessel Hardening Measures", "Vessel Hardening Measures", this.MdiParent, true);
//ERP_Ship.App_Code.Common.I_Common.StatusInfoLabel("Double Click the Search Record to View or Edit", "I", this.MdiParent, true);
}
private void gv_Appraisal_MouseUp(object sender, MouseEventArgs e)
{
hitTestGrid = gv_Appraisal.HitTest(e.X, e.Y);
if (hitTestGrid != null)
{
//Which column of datagrid has been clicked.
//switch (hitTestGrid.Column)
//{
if (hitTestGrid.Column == 3)
{
if (gv_Appraisal[gv_Appraisal.CurrentRowIndex, 2].ToString() == "T")
{
dataGridStyle.GridColumnStyles.Clear();
dataGridStyle.GridColumnStyles.Add(dataGridTextBox);
dataGridTextBox.HeaderText = "TEXTBOX_COL";
dataGridTextBox.MappingName = "TextBox_Col";
dataGridTextBox.Width = 130;
//Add texbox control to datagrid.
dataGridTextBox.TextBox.Controls.Add(txtControl);
// txtControl.Text = gv_Appraisal[gv_Appraisal.CurrentRowIndex, 3].ToString();
txtControl.Focus();
}
else if (gv_Appraisal[gv_Appraisal.CurrentRowIndex, 2].ToString() == "O")
{
dataGridStyle.GridColumnStyles.Clear();
dataGridStyle.GridColumnStyles.Add(dataGridComboBox);
dataGridComboBox.HeaderText = "COMBOBOX_COL";
dataGridComboBox.MappingName = "ComboBox_col";
dataGridComboBox.Width = 130;
//Add combobox control to datagrid.
dataGridComboBox.TextBox.Controls.Add(cboControl);
cboControl.Focus();
//for (int i = 0; i < cboControl.Items.Count; i++)
//{
// if (cboControl.Items[i].ToString() == gv_Appraisal[gv_Appraisal.CurrentRowIndex, 3].ToString())
// cboControl.SelectedIndex = i;
//}
}
}
}
}
private void txtTextChanged(object sender, System.EventArgs e)
{
ds.Tables["Apprdtl"].Rows[gv_Appraisal.CurrentRowIndex]["TextBox_Col"] = txtControl.Text;
}
//Combobox selected index changed event.
private void cboSelectedIndexChanged(object sender, System.EventArgs e)
{
ds.Tables["Apprdtl"].Rows[gv_Appraisal.CurrentRowIndex]["TextBox_Col"] = cboControl.Text;
}
}
}
There might be multiple approaches to implement functionality, you are looking for.
I found one sample on this link
Check if approach described there suits to your current requirement needs.
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;
}
}
}
What I am trying to do is to populate column of GridView with textboxes and to execute some function OnTextChanged.
This is my code:
if (e.Row.RowType == DataControlRowType.DataRow)
{
UpdatePanel UP_AmountToBuy = new UpdatePanel();
UP_AmountToBuy.ContentTemplateContainer.Controls.Clear();
UP_AmountToBuy.Triggers.Clear();
UP_AmountToBuy.UpdateMode = UpdatePanelUpdateMode.Conditional;
UP_AmountToBuy.ChildrenAsTriggers = false;
UP_AmountToBuy.Attributes["runat"] = "server";
//Create and add TextBox
TextBox TB_AmountToBuy = new TextBox();
TB_AmountToBuy.Text = "0";
TB_AmountToBuy.TextChanged += new EventHandler(TB_AmountToBuy_TextChanged);
TB_AmountToBuy.Attributes["OnTextChanged"] = "TB_AmountToBuy_TextChanged";
TB_AmountToBuy.Attributes["runat"] = "server";
TB_AmountToBuy.AutoPostBack = true;
TB_AmountToBuy.ViewStateMode = System.Web.UI.ViewStateMode.Enabled;
TB_AmountToBuy.ID = "buyID" + count;
UP_AmountToBuy.ContentTemplateContainer.Controls.Add(TB_AmountToBuy);
//Create and add AsyncPostBackTrigger
AsyncPostBackTrigger APBT_trig = new AsyncPostBackTrigger();
APBT_trig.EventName = "TextChanged";
APBT_trig.ControlID = TB_AmountToBuy.ID;
UP_AmountToBuy.Triggers.Add(APBT_trig);
Label newLBL = new Label();
newLBL.Text = "123";
newLBL.Attributes["runat"] = "server";
UP_AmountToBuy.ContentTemplateContainer.Controls.Add(newLBL);
e.Row.Cells[5].Controls.Add(UP_AmountToBuy);
count++;
}
}
public void TB_AmountToBuy_TextChanged(object sender, EventArgs e)
{
((sender as TextBox).Parent.Controls[1] as Label).Text = (sender as TextBox).Text;
}
The problem is, that event OnTextChanged never fired...
Dynamically generated controls needs to be created every time in page load in order to restore their view state ,fire events and get value from them.Like this
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var dt = new System.Data.DataTable();
dt.Columns.Add("Col1");
dt.Rows.Add("Hi");
GridView1.DataSource = dt;
GridView1.DataBind();
}
CreateDynamicControles();
}
public void CreateDynamicControles()
{
var count = 0;
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
UpdatePanel UP_AmountToBuy = new UpdatePanel();
UP_AmountToBuy.ContentTemplateContainer.Controls.Clear();
UP_AmountToBuy.Triggers.Clear();
UP_AmountToBuy.UpdateMode = UpdatePanelUpdateMode.Conditional;
UP_AmountToBuy.ChildrenAsTriggers = false;
UP_AmountToBuy.Attributes["runat"] = "server";
//Create and add TextBox
TextBox TB_AmountToBuy = new TextBox();
TB_AmountToBuy.Text = "0";
TB_AmountToBuy.TextChanged += new EventHandler(TB_AmountToBuy_TextChanged);
TB_AmountToBuy.Attributes["OnTextChanged"] = "TB_AmountToBuy_TextChanged";
TB_AmountToBuy.Attributes["runat"] = "server";
TB_AmountToBuy.AutoPostBack = true;
TB_AmountToBuy.ViewStateMode = System.Web.UI.ViewStateMode.Enabled;
TB_AmountToBuy.ID = "buyID" + count;
UP_AmountToBuy.ContentTemplateContainer.Controls.Add(TB_AmountToBuy);
//Create and add AsyncPostBackTrigger
AsyncPostBackTrigger APBT_trig = new AsyncPostBackTrigger();
APBT_trig.EventName = "TextChanged";
APBT_trig.ControlID = TB_AmountToBuy.ID;
UP_AmountToBuy.Triggers.Add(APBT_trig);
Label newLBL = new Label();
newLBL.Text = "123";
newLBL.Attributes["runat"] = "server";
UP_AmountToBuy.ContentTemplateContainer.Controls.Add(newLBL);
row.Cells[0].Controls.Add(UP_AmountToBuy);
count++;
}
}
}
public void TB_AmountToBuy_TextChanged(object sender, EventArgs e)
{
((sender as TextBox).Parent.Controls[1] as Label).Text = (sender as TextBox).Text;
}
}
Try this, since you are using UpdatePanel. So use following property.
Set property:
EnableViewstate="True"
I have three drop down lists and depending on the values selected in the lists I create dynamic controls accordingly. Everything displays properly but when I click on the dynamically created button the events are not firing. I am using the Page_LoadComplete to create the dynamic controls because I need to the values from the DDL's. Is this the reason for my button events not firing?
protected void Page_LoadComplete(object sender, EventArgs e)
{
queries = new clsFormQueries();
if (HttpContext.Current.User.IsInRole("Admin"))
{
if (!Page.IsPostBack)
{
List<Sport> sports = ComboBoxOptions.getSports();
DropDownList temp = (DropDownList)loginView2.FindControl("Sport");
temp.DataSource = sports;
temp.DataTextField = "Name";
temp.DataValueField = "id";
temp.DataBind();
DropDownList teamsDD = (DropDownList)loginView2.FindControl("Team");
List<Team> teamsList = ComboBoxOptions.getTeamsBySportId(Convert.ToInt32(temp.SelectedValue));
teamsDD.DataSource = teamsList;
teamsDD.DataTextField = "fullName";
teamsDD.DataValueField = "teamId";
teamsDD.DataBind();
DropDownList existingPlayers = (DropDownList)loginView2.FindControl("ExistingPlayers");
List<Player> players = ComboBoxOptions.getPlayersBySport(Convert.ToInt32(temp.SelectedValue), Convert.ToInt32(teamsDD.SelectedValue));
existingPlayers.DataSource = players;
existingPlayers.DataTextField = "fullName";
existingPlayers.DataValueField = "playerid";
existingPlayers.DataBind();
//if (existingPlayers.SelectedValue != "" && temp.SelectedValue != "")
//{
// DataTable updates = queries.GetPlayerUpdate(Convert.ToInt32(existingPlayers.SelectedValue), Convert.ToInt32(temp.SelectedValue));
// if (updates.Rows.Count > 0)
// CreateUpdatesHTML(updates);
//}
}
DropDownList temp2 = (DropDownList)loginView2.FindControl("Sport");
DropDownList existingPlayers2 = (DropDownList)loginView2.FindControl("ExistingPlayers");
if (existingPlayers2.SelectedValue != "" && temp2.SelectedValue != "")
{
DataTable updates = queries.GetPlayerUpdate(Convert.ToInt32(existingPlayers2.SelectedValue), Convert.ToInt32(temp2.SelectedValue));
if (updates.Rows.Count > 0)
CreateUpdatesHTML(updates);
}
}
}
private void CreateUpdatesHTML(DataTable updates)
{
foreach (DataRow update in updates.Rows)
{
int playerUpdateId = (int)update["playerUpdateId"];
string updateText = update["PlayerUpdate"].ToString();
TextBox tb = new TextBox();
tb.ID = "UpdateText" + playerUpdateId;
tb.TextMode = TextBoxMode.MultiLine;
tb.Rows = 5;
tb.Text = updateText;
tb.CssClass = "span5";
Button btnDelete = new Button();
btnDelete.Click += new EventHandler(btnDelete_Click);
btnDelete.ID = "Delete"+playerUpdateId.ToString();
btnDelete.Text = "Delete";
btnDelete.CssClass = "btn btn-info";
Button btnUpdate = new Button();
btnUpdate.Click += new EventHandler(btnUpdate_Click);
btnUpdate.ID = "Update"+playerUpdateId.ToString();
btnUpdate.Text = "Update";
btnUpdate.CssClass = "btn btn-info";
HtmlGenericControl div2 = new HtmlGenericControl("div");
div2.Attributes.Add("class", "pull-right span5");
div2.Controls.Add(btnDelete);
div2.Controls.Add(btnUpdate);
HtmlGenericControl hr = new HtmlGenericControl("hr");
HtmlGenericControl br = new HtmlGenericControl("br");
existingUpdates.Controls.Add(tb);
existingUpdates.Controls.Add(div2);
existingUpdates.Controls.Add(br);
existingUpdates.Controls.Add(hr);
}
}
My guess is that since you have wrapped the logic for your Page_LoadComplete event inside of a n if(!Page.IsPostBack), since the click of the button causes a postback, your dynamically created controls are not recreated properly (read: no click event handling is wired up). You need to have logic on every invocation of Page_LoadComplete (non-postback or postback) that recreates the dynamic controls and wires up their events.