how to create oncheckedchange for dynamic checkbox - c#

try
{
string constr1 = ConfigurationManager.ConnectionStrings["constring"].ConnectionString;
SqlConnection conn1 = new SqlConnection(constr1);
conn1.Open();
//passing a query to fetch the table from database,which is entered in TextBox
DataSet ds = new DataSet();
string s2 = "select neid,keyholder from tbl_controller_settings where axxesstype='2'";
SqlDataAdapter da = new SqlDataAdapter(s2, conn1);
da.Fill(ds);
DataTable dt = new DataTable();
dt = ds.Tables[0];
//creating a table dynamically
HtmlTable table = new HtmlTable();
HtmlTableRow tr = null;
HtmlTableCell tc = null;
//displaying labels for displaying column names in the table
tr = new HtmlTableRow();
for (int i = 0; i <=64; i++)
{
tc = new HtmlTableCell();
Label lbl = new Label();
if(i!=0)
lbl.Text = "Key"+" "+i.ToString();
lbl.ID = "lbl" +" "+i.ToString();
lbl.Style.Add("writing-mode", "rt-tb");
lbl.Style.Add("filter", "flipv");
tc.Height = "50px";
tc.Width = "150px";
tc.Controls.Add(lbl);
tr.Controls.Add(tc);
table.Controls.Add(tr);
}
//creating textboxes for displaying records information
for (int j = 0; j < dt.Rows.Count; j++)
{
tr = new HtmlTableRow();
tc = new HtmlTableCell();
Label ksid = new Label();
ksid.ID = "ksid"+j;
ksid.Text = dt.Rows[j][0].ToString();
tc.Controls.Add(ksid);
tr.Controls.Add(tc);
for (int k = 1; k <= 64;k++ )
{
tc = new HtmlTableCell();
CheckBox chk = new CheckBox();
chk.ID = "txt" + j + k;
chk.CheckedChanged += new EventHandler(CheckBox_CheckedChanged);
if (k <= Convert.ToInt32(dt.Rows[j][1]))
chk.Enabled = true;
else
chk.Enabled = false;
tc.Controls.Add(chk);
tr.Controls.Add(tc);
}
table.Controls.Add(tr);
}
pnlkeys.Controls.Add(table);
pnlkeys.Visible = true;
//}
}
catch (Exception ex)
{
throw;
}
Hello
In the Above code i have created the check box and a label button dynamically,in this 64 iteration i will be having the 64 check box.i want to get the value has when a check box is checked it should be 1 and when it is not checked it should be 0 to store in 64 columns ..please help me

try add the method in the same class file :
public static void CheckBox_CheckedChanged(object sender, EventArgs e) {
}
If you want help on how to generate the "1" when checked, please specify first where that value is to be stored.

You do not need OnCheckedChanged if you want to store their values altogether.
You can access your CheckBox's value in PostBack on Request.Form with their ID
if(Request.Form["txt11"]==null)
{
//checkbox is not checked
}
if(Request.Form["txt11"]=="on")
{
//checkbox is checked
}
You need to write this code in a loop to get all your CheckBoxes

Related

how can i get values of gridview that i created in code behind when i click button

I have a problem about getting values from gridview that i created in code behind.
I created dynamic gridview. I filled DataSource from Database. These are my codes:
SqlCommand cmd = new SqlCommand("xxx", noz);
cmd.CommandType = CommandType.StoredProcedure;
noz.Open();
i = 1;
SqlDataReader rd = cmd.ExecuteReader();
if (rd.HasRows)
{
while (rd.Read())
{
string isim = "name" + i;
Label name4 = new Label();
name4.ID = isim;
name4.Text = rd3[1].ToString() + " için değerlendirme yapınız";
name4.Font.Bold = true;
ph.Controls.Add(name4);
noz2.Open();
SqlDataAdapter sda = new SqlDataAdapter("xxx", noz2);
sda.SelectCommand.CommandType = CommandType.StoredProcedure;
GridView gv = new GridView();
gv.ID = "_gridview" + i;
Queue q = new Queue();
q.Enqueue(i);
DataTable dt = new DataTable();
sda.Fill(dt);
dt.Columns.Add("Puanlar", typeof(string));
gv.DataSource = dt;
gv.DataBind();
ph.Controls.Add(gv); //ph is my placeholder//
gv.Height = 500;
gv.Width = 980;
i++;
noz2.Close();
foreach (GridViewRow r in gv.Rows)
{
TextBox ddl3Selection = new TextBox();
ddl3Selection.Width = 800;
r.Cells[2].Controls.Add(ddl3Selection);
}
}
noz.Close();
I have no problem so far. But when i want to use click button, i can't get gridviews's rows. I get rowcount 0.
for (int a = 1; a < i; a++)
{
GridView gv = new GridView();
gv.ID = "_gridview" + a;
Label lbl = new Label();
lbl.ID = "name" + a;
for (int n = 0; n < gv.Rows.Count; n++)
{
SqlCommand cmd = new SqlCommand("xxx", noz);
cmd.CommandType = CommandType.StoredProcedure;
GridViewRow row = gv.Rows[n];
int soruid =Convert.ToInt16(row.Cells[0].Text);
string cevap = row.Cells[2].Text;
string firmaadi = lbl.Text;
cmd.Parameters.AddWithValue("#Firma_Ad", firmaadi);
cmd.Parameters.AddWithValue("#Soru_Id", soruid);
cmd.Parameters.AddWithValue("#Soru_Cevap", cevap);
cmd.Parameters.AddWithValue("#Cevaplayan", "");
noz.Open();
int rd2 = cmd.ExecuteNonQuery();
noz.Close();
}
How can i get values from gridview?
there is two different grid. First grid have data source and the second is nothing.

ASP.NET C# How to generate dynamic Control

I'm using asp.net c# and I want to generate textbox from database. I have 4 records in my table so i want 4 textbox at run time.
But I'm getting only one textbox when checking in Insepct Element I get 4 textboxes but it does't show on my page.
Not sure where it went wrong.
I'm using code like this
OracleConnection obj_Conn = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OracleConn"].ToString());
Table table = new Table();
table.ID = "table1";
string Query = "SELECT * FROM XXCUS.MASTER_VERIFICATION";
OracleDataAdapter da = new OracleDataAdapter(Query, obj_Conn);
//DataSet ds = new DataSet();
DataTable dt = new DataTable();
da.Fill(dt);
var Count = dt.Rows.Count;
if (Count > 0)
{
TableRow row = new TableRow();
TextBox txt = new TextBox();
for (int i = 0; i < Count; i++)
{
TableCell cell = new TableCell();
txt.ID = "txt" + i.ToString();
cell.ID = "cell" + i.ToString();
cell.Controls.Add(txt);
row.Cells.Add(cell);
}
table.Rows.Add(row);
dvGenerateCntrl.Controls.Add(table);
}
and call this method on Page Load
put the line which declare a new TextBox inside of for loop
for (int i = 0; i < Count; i++)
{
TextBox txt = new TextBox();
TableCell cell = new TableCell();
txt.ID = "txt" + i.ToString();
cell.ID = "cell" + i.ToString();
cell.Controls.Add(txt);
row.Cells.Add(cell);
}
First debug your code and make sure that you get 4 rows in your datatable and use this code.
OracleConnection obj_Conn = new `OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["oracleConn"].ToString());`
Table table = new Table();
table.ID = "table1";
string Query = "SELECT * FROM XXCUS.MASTER_VERIFICATION";
OracleDataAdapter da = new OracleDataAdapter(Query, obj_Conn);
//DataSet ds = new DataSet();
DataTable dt = new DataTable();
da.Fill(dt);
var Count = dt.Rows.Count;
if (Count > 0)
{
TableRow row = new TableRow();
TextBox txt = new TextBox();
for (int i = 0; i < Count; i++)
{
TextBox txt = new TextBox();
TableCell cell = new TableCell();
txt.ID = "txt" + i.ToString();
cell.ID = "cell" + i.ToString();
cell.Controls.Add(txt);
row.Cells.Add(cell);
}
table.Rows.Add(row);
dvGenerateCntrl.Controls.Add(table);
}
In your code you don't create object of TextBox every time.
I think it will help you.

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

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

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

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

want multiple html data table in my asp.net form?

I am using one htmltable in my asp.net form but I want multiple htmltables at runtime like when I click on submit its selects releated data in my htmldatattable
I want to see particular id record in my particular htmltable which generated at run time how can i do this?
here is my htmltable code
protected void Page_Load(object sender, EventArgs e)
{
HtmlTable dTable = new HtmlTable();
dTable.CellPadding = 2;
// dTable.CellSpacing = 0;
dTable.Border = 1;
dTable.BorderColor = "#cccccc";
int tRows;
int tCells;
for (tRows = 0; tRows < 1; tRows++)
{
HtmlTableRow dTRow = new HtmlTableRow();
HtmlTableRow dtrow = new HtmlTableRow();
HtmlTableRow dtrow3 = new HtmlTableRow();
HtmlTableRow dtrow4 = new HtmlTableRow();
for (tCells = 0; tCells < 1; tCells++)
{
HtmlTableCell dTCell = new HtmlTableCell();
HtmlTableCell dtcell1 = new HtmlTableCell();
HtmlTableCell dtcell3 = new HtmlTableCell();
HtmlTableCell dtcell4 = new HtmlTableCell();
HtmlInputText txt = new HtmlInputText();
HtmlInputText txt1 = new HtmlInputText();
HtmlInputText txtAge = new HtmlInputText();
HtmlInputText txtHeight = new HtmlInputText();
dTCell.InnerText = "FirstName:: " + Convert.ToString(tRows);
dtcell1.InnerText = "LastName::" + Convert.ToString(tRows);
dtcell3.InnerText = "Age::" + Convert.ToInt32(tRows);
dtcell4.InnerText = "Height::" + Convert.ToString(tRows);
dTCell.Controls.Add(txt);
dtcell1.Controls.Add(txt1);
dtcell3.Controls.Add(txtAge);
dtcell4.Controls.Add(txtHeight);
dtrow.Controls.Add(dtcell1);
dtrow3.Controls.Add(dtcell3);
dtrow4.Controls.Add(dtcell4);
dTRow.Controls.Add(dTCell);
}
dTable.Controls.Add(dTRow);
dTable.Controls.Add(dtrow);
dTable.Controls.Add(dtrow3);
dTable.Controls.Add(dtrow4);
Panel1.Controls.Add(dTable);
}
Try moving your code into Init() method, not page_load.
Also this topic can help.

Categories