I added CheckBox controls dynamically from the database to FlowLayOutPanel. How do I get and store all selected values?
My sample code is here...
private void dynamicCheck()
{
//throw new NotImplementedException();
DataSet1TableAdapters.tbl_subjects1TableAdapter ta =
new DataSet1TableAdapters.tbl_subjects1TableAdapter();
DataTable dt = ta.GetData();
foreach (DataRow row in dt.Rows)
{
CheckBox chk = new CheckBox();
chk.Width = 90;
chk.Text = row[1].ToString();
chk.CheckedChanged += new
EventHandler(changeCheck);
flowLayoutPanel1.Controls.Add(chk);
}
}
private void changeCheck(object sender, EventArgs e)
{
//throw new NotImplementedException();
CheckBox chk = sender as CheckBox;
if (chk.Checked)
{
//MessageBox.Show("checked item" + chk.Text);
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
}
I'd do this:
private List<CheckBox> _checkBoxes = null;
private void DynamicCheck()
{
DataSet1TableAdapters.tbl_subjects1TableAdapter ta =
new DataSet1TableAdapters.tbl_subjects1TableAdapter();
DataTable dt = ta.GetData();
_checkBoxes = dt.Rows.Cast<DataRow>().Select(row =>
{
CheckBox chk = new CheckBox();
chk.Width = 90;
chk.Text = row[1].ToString();
chk.CheckedChanged += new EventHandler(changeCheck);
flowLayoutPanel1.Controls.Add(chk);
return chk;
}).ToList();
}
Now you can access each CheckBox in _checkBoxes.
Related
Currently, there is 2 values in my DropDownList which is viewProduct and editProduct. So when the user selects one of the value, it will direct user to the particular function in ASP.NET. I have tried OnSelectedIndexChanged, but it seems like not working on the dynamic DropDownList.
Here is my code:
ddlAction.ID = "ddlForAction";
ddlAction.CssClass = "ddlList";
ddlAction.CausesValidation = false;
ddlAction.AutoPostBack = true;
ddlAction.Items.Add(new ListItem("View","viewProduct"));
ddlAction.Items.Add(new ListItem("Edit", "editProduct"));
e.Row.Cells[5].Controls.Add(ddlAction);
if(ddlAction.SelectedValue == "editProduct")
{
editProduct();
}
else if(ddlAction.SelectedValue == "viewProduct")
{
retrieveProduct();
}
Any idea how to solve it without using JavaScript?
My entire code:
protected void Page_Load(object sender, EventArgs e)
{
BindGridView();
}
private void BindGridView()
{
MySqlConnection conn = new MySqlConnection(sqlConn);
string sql = "SELECT prodID, prodName, stockLevel, reorderLevel, unitPrice from Product";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
productList.DataSource = dt;
productList.DataBind();
}
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
TableCell tc = new TableCell();
DropDownList ddlAction = new DropDownList();
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Text = "Prod ID";
e.Row.Cells[1].Text = "Product Name";
e.Row.Cells[2].Text = "Qty";
e.Row.Cells[3].Text = "Reorder Level";
e.Row.Cells[4].Text = "Price (RM)";
e.Row.Controls.Add(tc);
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
var qty = Int16.Parse(e.Row.Cells[2].Text);
var reorder = Int16.Parse(e.Row.Cells[3].Text);
if (qty <= reorder)
{
e.Row.Cells[2].CssClass = "redCell";
e.Row.Cells[3].CssClass = "redCell";
}
e.Row.Controls.Add(tc);
ddlAction.ID = "ddlForAction";
ddlAction.CssClass = "ddlList";
ddlAction.CausesValidation = false;
ddlAction.AutoPostBack = true;
ddlAction.Items.Add(new ListItem("View","viewProduct"));
ddlAction.Items.Add(new ListItem("Edit", "editProduct"));
e.Row.Cells[5].Controls.Add(ddlAction);
ddlAction.SelectedIndexChanged += DDLAction_OnSelectedIndexChanged;
if (ddlAction.SelectedValue == "editProduct")
{
editProduct();
}
else if (ddlAction.SelectedValue == "viewProduct")
{
retrieveProduct();
}
}
}
You need to declare an event handler then assign it to the control before adding the control to the page.
Here is an example :
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
CreateControl();
}
}
protected void CreateControl()
{
var ddlAction = new DropDownList();
ddlAction.ID = "ddlForAction";
ddlAction.CssClass = "ddlList";
ddlAction.CausesValidation = false;
ddlAction.AutoPostBack = true;
ddlAction.Items.Add(new ListItem("View","viewProduct"));
ddlAction.Items.Add(new ListItem("Edit", "editProduct"));
ddlAction.SelectedIndexChanged += DDLAction_OnSelectedIndexChanged;
e.Row.Cells[5].Controls.Add(ddlAction);
}
protected void DDLAction_OnSelectedIndexChanged(object sender, EventArgs e)
{
var action = (DropDownList) sender;
var choice = action.SelectedValue?.Trim();
string script = null;
switch (choice)
{
case "viewProduct":
script = "alert('View page!');";
break;
case "editProduct":
script = "alert('Edit page!');";
break;
default:
script = "alert('Unmatched Value!')";
break;
}
ScriptManager.RegisterStartupScript(this , typeof(_Default) , "TestJS" , $"<script>{script}</script>" , false);
}
use ScriptManager.RegisterStartupScript when you want to work with JS scripts. Response.Write will not parse script blocks as an executable blocks. It will throw a parse error though (you could check the browser console.
I've created some dynamic checkboxes in table header row.
If the checkbox is checked , table will have another row with a textbox.
Checkbox changed event is firing very well but when I'm trying to check whether the checkbox is checked or not , it's generating exception :
Object Reference not set to an instance of an object.
Here is my code :
Creating Dynamic controls here :
TableRow thead = new TableRow();
for (int i = 0; i < dt_fundtype.Rows.Count; i++)
{
TableCell td = new TableCell();
CheckBox chk = new CheckBox();
chk.ID = "fund_" + dt_fundtype.Rows[i]["fund_type_cd"];
chk.Text = dt_fundtype.Rows[i]["fund_type"].ToString();
chk.AutoPostBack = true;
chk.CheckedChanged += new EventHandler(Chk_Fund_CheckedChange);
td.Controls.Add(chk);
thead.Cells.Add(td);
}
tbl_fundtype.Rows.Add(thead);
Checkbox checked changed event :
public void Chk_Fund_CheckedChange(object sender, EventArgs e)
{
TableRow tr = new TableRow();
for (int i=0;i<tbl_fundtype.Rows[0].Cells.Count;i++)
{
string DynamicChkID ="fund_"+ dt_fundtype.Rows[i]["fund_type_cd"].ToString();
CheckBox chk = new CheckBox();
chk = (CheckBox)tbl_fundtype.Rows[0].Cells[i].FindControl("DynamicChkID");
if (chk.Checked == true)//Here is the Exception
{
TableCell td = new TableCell();
td.Text = "Test";
tr.Cells.Add(td);
}
}
tbl_fundtype.Rows.Add(tr);
hfTab.Value = "fund";
collapsestate = "expand";
}
The event is firing very well , but when I check that the checkbox is checked or not there's an exception.
How can I resolve this problem ? Kindly Help me Please
This is the example I use which work for me.
I've simplified the binding logic and lookup logic etc, to illustrate
protected void Page_Load(object sender, EventArgs e)
{
AddStuff();
}
private void AddStuff()
{
TableRow thead = new TableRow();
for (int i = 0; i < 10; i++)
{
TableCell td = new TableCell();
CheckBox chk = new CheckBox();
chk.ID = "fund_" + i;
chk.Text = i.ToString();
chk.AutoPostBack = true;
chk.CheckedChanged += new EventHandler(Chk_Fund_CheckedChange);
td.Controls.Add(chk);
thead.Cells.Add(td);
}
tbl_fundtype.Rows.Add(thead);
}
public void Chk_Fund_CheckedChange(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
var chk = tbl_fundtype.FindControl("fund_" + i) as CheckBox;
if (chk.Checked)
{
//I am checked
}
}
}
And on my markup page I have:
<asp:Table ID="tbl_fundtype" runat="server" />
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = Rowcreation();
TableRow thead = new TableRow();
for (int i = 0; i < dt.Rows.Count; i++)
{
TableCell td = new TableCell();
CheckBox chk = new CheckBox();
chk.ID = "fund" + dt.Rows[i]["ID"];
chk.Text = dt.Rows[i]["Name"].ToString();
chk.AutoPostBack = true;
chk.CheckedChanged += new EventHandler(chk_fun_checkedchange);
td.Controls.Add(chk);
thead.Controls.Add(td);
}
pnl.Controls.Add(thead);
}
public void chk_fun_checkedchange(object sender, EventArgs e)
{
DataTable dt = Rowcreation();
for (int i = 0; i < dt.Rows.Count; i++)
{
CheckBox chkbx = (CheckBox ) pnl.Parent.Controls[0].FindControl("fund"+dt.Rows [i]["ID"]);
if (chkbx.Checked == true)
{
lbl.Text = chkbx.Text;
}
}
}
private DataTable Rowcreation()
{
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
DataRow dr = dt.NewRow();
dr["ID"] = "1";
dr["Name"] = "Name1";
dt.NewRow();
dt.Rows.Add(dr);
DataRow dr1 = dt.NewRow();
dr1["ID"] = "2";
dr1["Name"] = "Name2";
dt.Rows.Add(dr1);
dt.NewRow();
DataRow dr2 = dt.NewRow();
dr2["ID"] = "3";
dr2["Name"] = "Name3";
dt.Rows.Add(dr2);
return dt;
}
I am creating a dynamically repeater during the creation of this repeater I create some dropdownlists with autopostback = true, and add the handler selectindexchanged. I wonder how to keep bind the repeater inside (! IsNotPostBack) without losing the repeater information. In summary if I keep bind the repeater in notpostback, when I change the dropdownlist the repeater is not rendered.
Well confused? I will post part of the code:
Default.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindRepeater2();
}
}
private void BindRepeater2()
{
Repeater rContainer = null;
HtmlGenericControl div = new HtmlGenericControl("div");
HtmlGenericControl table = new HtmlGenericControl("table");
div.Attributes.Add("class", "CompApp_TableScroll");
table.Attributes.Add("class", "CompApp_DataTable");
table.Attributes.Add("width", "100%");
try
{
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Address", typeof(string));
dt.Columns.Add("DropDown", typeof(string));
dt.Rows.Add(25, "Rk", "Gurgaon");
dt.Rows.Add(50, "Sachin", "Noida");
dt.Rows.Add(10, "Nitin", "Noida");
dt.Rows.Add(21, "Aditya", "Meerut");
DataSet ds = new DataSet();
ds.Tables.Add(dt);
if (dt.Rows.Count > 0)
{
rContainer = new Repeater();
rContainer.DataSource = dt;
rContainer.DataBind();
foreach (DataTable dtCluster in ds.Tables)
{
rContainer = new Repeater();
rContainer.ItemTemplate = new RepeaterTemplate2(ListItemType.Item);
rContainer.HeaderTemplate = new RepeaterTemplate2(ListItemType.Header);
rContainer.FooterTemplate = new RepeaterTemplate2(ListItemType.Footer);
rContainer.DataSource = dtCluster;
table.Controls.Add(rContainer);
}
div.Controls.Add(table);
}
div1.Controls.Add(div);
rContainer.ItemDataBound += rContainer_ItemDataBound;
rContainer.ID = "rpt1";
rContainer.DataBind();
}
catch (Exception ex)
{
throw ex;
}
}
void rContainer_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList ddl = new DropDownList();
ddl = (DropDownList)e.Item.FindControl("ddl");
ddl.AutoPostBack = true;
ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
}
}
private void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl2 = new DropDownList();
ddl2 = (DropDownList)sender;
Response.Write(ddl2.SelectedValue);
}
RepeaterTemplate2.cs
public class RepeaterTemplate2 : System.Web.UI.ITemplate
{
ListItemType vTemplateItemType = ListItemType.Separator;
public RepeaterTemplate2(ListItemType pListItemType)
{
vTemplateItemType = pListItemType;
}
public void InstantiateIn(System.Web.UI.Control container)
{
Literal lc = new Literal();
HtmlGenericControl tr = new HtmlGenericControl("tr");
HtmlGenericControl td = new HtmlGenericControl("td");
switch (vTemplateItemType)
{
case ListItemType.Header:
td.InnerHtml = "<u>EmpID</u>";
tr.Controls.Add(td);
td = new HtmlGenericControl("td");
td.InnerHtml = "<u>Name</u>";
tr.Controls.Add(td);
td = new HtmlGenericControl("td");
td.InnerHtml = "<u>Address</u>";
tr.Controls.Add(td);
td = new HtmlGenericControl("td");
td.InnerHtml = "<u>DropdDown</u>";
tr.Controls.Add(td);
break;
case ListItemType.Footer:
break;
case ListItemType.Item:
; break;
}
tr.DataBinding += new EventHandler(lc_DataBinding);
container.Controls.Add(tr);
}
private void lc_DataBinding(object sender, EventArgs e)
{
HtmlGenericControl tr = (HtmlGenericControl)sender;
RepeaterItem vContainer = (RepeaterItem)tr.NamingContainer;
DataRowView row = (DataRowView)vContainer.DataItem;
if (row != null)
{
for (int i = 0; i < row.DataView.Table.Columns.Count; i++)
{
HtmlGenericControl td = new HtmlGenericControl("td");
if (i == 3)
{
DropDownList ddl = new DropDownList();
ddl.ID = "ddl";
ddl.Items.Add(new ListItem("valor 1", "1"));
ddl.Items.Add(new ListItem("valor 2", "2"));
td.Controls.Add(ddl);
}
else
{
td.InnerHtml = row[i].ToString();
}
tr.Controls.Add(td);
}
}
}
}
private void tabControl1_Selected(object sender, TabControlEventArgs e)
{
if (e.TabPage.Name == tabPage2.Name)
{
table = Items.Get();
comboBox1.DataSource = table;
comboBox1.DisplayMember = "Item_ID";
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable temp = new DataTable();
string text = comboBox1.SelectedItem.ToString();
temp = Color.Get(text);
comboBox2.DataSource = temp;
comboBox2.DisplayMember = "Color_Name";
comboBox2.ValueMember = "Color_ID";
}
I am trying to populate the comboBox1 as the tabpage open and then populate the comboBox2 based on the selectedText of comboBox1.
comboBox_SelectedIndexChange runs 2 times when tab changes but returns null every times.
Note: I have already appended event handler as the form initializes like,
public Form1()
{
InitializeComponent();
tabControl1.Selected += new TabControlEventHandler(tabControl1_Selected);
comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
table = new DataTable();
s = new Stock();
}
First there is a bug in
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable temp = new DataTable();
string text = comboBox1.SelectedItem.ToString();
temp = Color.Get(text);
comboBox2.DataSource = temp;
comboBox2.DisplayMember = "Color_Name";
comboBox2.ValueMember = "Color_ID";
}
code. You override value for datasource in line
temp = Color.Get(text);
I think it should be like:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable temp = new DataTable();
string text = comboBox1.SelectedItem.ToString();
selectedColor = Color.Get(text);
comboBox2.DataSource = temp;
comboBox2.DisplayMember = "Color_Name";
comboBox2.ValueMember = "Color_ID";
comboBox2.SelectedItem = selectedColor;
}
I don't know contents of DataTable so instead of comboBox2.SelectedItem you may need to set SelectedItem, SelectedText or SelectedValue properties of comboBox2.
Suspicious line here:
string text = comboBox1.SelectedItem.ToString();
You will get text variable filled with "YourNamespace.DataTable". If your function Color.Get(text) is expecting Item_ID of selected item as parameter, then you should change that line of code above to:
string text = ((DataTable)comboBox1.SelectedItem).Item_ID;
I assumed that DataTable is an object that have Item_ID property.
private void tabControl1_Selected(object sender, TabControlEventArgs e)
{
if (e.TabPage.Name == tabPage2.Name)
{
table = Items.Get();
if (table.Rows.Count > 0)
{
//Update comboBox1 using table
comboBox1.DataSource = table;
comboBox1.DisplayMember = "Item_ID";
//Using 1st row and 1st coloumn in function argument to get colors
//Color.Get(string itemID) returns dataTable, which I used for comboBox2 DataSource
comboBox2.DataSource = Color.Get(table.Rows[0].ItemArray[0].ToString());
comboBox2.ValueMember = "Color_ID";
comboBox2.DisplayMember = "Color_Name";
}
}
}
private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
{
string sid;
try
{
txtOut.Clear();
sid = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["ServerType"].Value.ToString();
txtOut.Text = sid;
txtOut.Refresh();
}
catch(Exception)
{
}
List<string> lst2 = new List<string> ();
DataGridView dgv1 = new DataGridView();
//load dgv1 with the rows
foreach(DataGridViewRow r in dataGridView1.SelectedRows)
{
dgv1.Rows.Add(r);
string scolumn = r.DataGridView.Columns.Equals(3).ToString();
txtOut.Text = r.ToString();
txtOut.Refresh();
}
string[] q1 = lst2.Distinct().ToArray();
listBox1.DataSource = q1;
}