Dynamically created controls in Page_Load() - c#

I have a question regarding creating controls in runtime in ASP.NET 4.0. I'm building a application and in admin.aspx page I have multiple controls (DropDownLists) which are dynamically created with values from a Sql database.
I know that for having events fired for dynamically created controls, I have to create this controls in Page_Load() or in Page_Init().
My project has a Master Page, in which I have a 1 second timer which updates a clock. This timer event calls my admin.aspx Page_Load() function, so my method which creates dynamic controls it's called every 1 second - connection to database is made every one second, please look below to my code.
It's a good practice to do that? Can you please propose some ideas?
protected void Page_Load(object sender, EventArgs e)
{
_SinopticBackgroundColor = ConfigurationManager.AppSettings["SinopticBackgroundColor"];
panelContent.Style.Add("background-color", _SinopticBackgroundColor);
Control c = GetControlThatCausedPostBack(this);
if (c != null)
{
if (c.ID.Equals("btnManageCategory"))
hfPageManage.Value = "category";
else if (c.ID.Equals("btnManageDevices"))
hfPageManage.Value = "device";
}
if (hfPageManage.Value.Equals("category"))
{
cbTreeViewGroup.Visible = false;
UpdateSinopticCategoryManager(TreeView1.SelectedNode); //this is the functions which loads controls from database..
}
else if (hfPageManage.Value.Equals("device"))
{
cbTreeViewGroup.Visible = true;
}
else
{
cbTreeViewGroup.Visible = false;
}
if (!Page.IsPostBack)
{
LoadFunctions(); // loads some values from database into datatables
}
else
{
}
}
And here is the functions which creates controls
private void UpdateSinopticCategoryManager(TreeNode node = null)
{
if (node == null)
return;
DataTable categoriiDT = null;
using (var connection = new SqlConnection(Database.ConnectionString))
{
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT * FROM categories WHERE CategoryID = #CategoryID";
command.Parameters.Add("CategoryID", node.Value);
SqlDataAdapter ad = new SqlDataAdapter(command);
DataSet ds = new DataSet("CATEGORYPROPERTIES");
connection.Open();
ad.Fill(ds);
// verificam sa avem date
if (ds.Tables.Count <= 0)
return;
if (ds.Tables[0].Rows.Count <= 0)
return;
categoriiDT = ds.Tables[0];
}
}
// generate table
Table table = new Table();
table.Style.Add("position", "relative");
table.Style.Add("top", "20px");
table.Style.Add("margin-left", "20px");
table.BorderStyle = BorderStyle.Solid;
table.BorderWidth = 1;
// header
TableHeaderRow hr = new TableHeaderRow();
for (int i = 0; i < 2; i++)
{
TableHeaderCell hc = new TableHeaderCell();
if (i > 0)
{
hc.Text = "FUNCTION";
//hc.Width = 200;
}
else
{
hc.Width = 100;
}
hr.Cells.Add(hc);
}
table.Rows.Add(hr);
var inputs = (from a in categoriiDT.Columns.Cast<DataColumn>()
where a.ColumnName.ToLowerInvariant().Contains("input")
select a.ColumnName).ToArray();
if (inputs.Count() <= 0)
return;
//rows input
for (int i = 0; i < inputs.Count(); i++)
{
TableRow tableRow = new TableRow();
for (int j = 0; j < 2; j++)
{
TableCell cell = new TableCell();
if (j > 0)
{
// adaugare 2 dropdownlist
DropDownList categList = new DropDownList();
categList.SelectedIndexChanged += new EventHandler(categList_SelectedIndexChanged);
foreach (DataRow row in functionsCategories.Rows)
{
categList.Items.Add(new ListItem(row["FunctionCategoryName"].ToString(), row["FunctionCategoryID"].ToString()));
}
DropDownList funcList = new DropDownList();
int selF = 0, selC = 0;
for (int fi = 0; fi < functions.Rows.Count; fi++)// (DataRow row in functions.Rows)
{
funcList.Items.Add(new ListItem(functions.Rows[fi]["FunctionName"].ToString(), functions.Rows[fi]["FunctionID"].ToString()));
if (functions.Rows[fi]["FunctionID"].ToString() == categoriiDT.Rows[0][inputs[i]].ToString())
{
selF = fi;
selC = Int32.Parse(functions.Rows[fi]["FunctionCategoryID"].ToString());
}
}
funcList.SelectedIndex = selF;
categList.SelectedIndex = functionsCategories.Rows.IndexOf(
(from c in functionsCategories.AsEnumerable()
where c["FunctionCategoryID"].ToString().Equals(selC.ToString())
select c).FirstOrDefault());
cell.Controls.Add(categList);
cell.Controls.Add(funcList);
}
else
{
Label label = new Label();
label.Text = "INPUT " + i.ToString();
label.Style.Add("font-weight", "bold");
cell.Controls.Add(label);
}
tableRow.Cells.Add(cell);
}
table.Rows.Add(tableRow);
}
//rows output
for (int i = 0; i < 4; i++)
{
TableRow row = new TableRow();
for (int j = 0; j < 2; j++)
{
TableCell cell = new TableCell();
if (j > 0)
{
DropDownList list = new DropDownList();
list.Width = 200;
list.Items.AddRange(GetOutputFunctions());
list.BorderColor = Color.Goldenrod;
cell.Controls.Add(list);
}
else
{
Label label = new Label();
label.Text = "OUTPUT " + i.ToString();
label.Style.Add("font-weight", "bold");
cell.Controls.Add(label);
}
row.Cells.Add(cell);
}
table.Rows.Add(row);
}
// add table to panel
panelContent.Controls.Add(table);
}
It's about this: DropDownList categList = new DropDownList();

This may get answered more quickly and effectively in codereview https://codereview.stackexchange.com/

Related

How to get the values of button templatefield in Gridview?

I want to display the row details of Gridview when user click the button of template field. I got the output to display the button in a Gridview using template field. But when user click the button it reload the page and display the empty template with rows.
Full Coding of c#
string selectedColumn;
string[] splitSelectedColumn;
string groupByColumn;
string[] splitGroupByColumn;
ArrayList listBtnOrLbl = new ArrayList();
int compareFlag = 0;
protected void btnRefresh_Click(object sender, EventArgs e)
{
selectedColumn = txtColumnNames.Text;
splitSelectedColumn = selectedColumn.Split(',');
groupByColumn = txtGroupBy.Text;
splitGroupByColumn = groupByColumn.Split(',');
string[] compareGroup = new string[splitGroupByColumn.Length];
//Grouping column names using selected column text
int flag = 1;
foreach (string columnName in splitSelectedColumn)
{
flag = 1;
foreach (string groupByName in splitGroupByColumn)
{
if (columnName.Equals(groupByName))
{
flag = 2;
break;
}
}
if (flag == 1)
{
groupByColumn = groupByColumn + "," + columnName;
}
}
// CREATE A TEMPLATE FIELD AND BOUND FIELD
BoundField bfield = new BoundField();
TemplateField[] ttfield = new TemplateField[splitGroupByColumn.Length];
for (int i = 0; i < splitSelectedColumn.Length; i++)
{
if (i < splitGroupByColumn.Length)
{
ttfield[i] = new TemplateField();
ttfield[i].HeaderText = splitGroupByColumn[i];
GridView1.Columns.Add(ttfield[i]);
}
else
{
try
{
bfield.HeaderText = splitSelectedColumn[i];
bfield.DataField = splitSelectedColumn[i];
Response.Write("<br/>BOUND FIELD==" + splitGroupByColumn[i]);
GridView1.Columns.Add(bfield);
}
catch (Exception)
{
}
}
}
// CREATE DATA TABLE and COLUMN NAMES
DataTable dt = new DataTable();
//dt.Columns.Clear();
for (int i = 0; i < splitSelectedColumn.Length; i++)
{
dt.Columns.Add(splitSelectedColumn[i]);
//Console.WriteLine(splitSelectedColumn[i]);
System.Diagnostics.Debug.WriteLine(splitSelectedColumn[i]);
Response.Write("<br/>DT COLUMN NAMES==" + splitSelectedColumn[i]);
}
//ADD ROWS FROM DATABASE
string cs = ConfigurationManager.ConnectionStrings["connectionStringDB"].ConnectionString;
//int compareFlag = 0;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
//cmd.CommandText = "select " + selectedColumn + " FROM [RMSDemo].[dbo].[ItemRelation] where ItemLookupCode='" + txtItemLookupCode.Text + "'and ChildItemLookupCode1='" + txtChildItemLookupCode.Text + "' group by " + groupByColumn + " ";
cmd.CommandText = "select " + selectedColumn + " FROM [RMSDemo].[dbo].[ItemRelation] group by " + groupByColumn + " ";
con.Open();
SqlDataReader rd = cmd.ExecuteReader();
string addData = string.Empty;
string[] stackss = new string[splitSelectedColumn.Length];
while (rd.Read())
{
//SET the FIRST VALUES in `stackss[]` for comparing next values of rd[]
if (compareFlag == 0)
{
for (int i = 0; i < splitGroupByColumn.Length; i++)
{
compareGroup[i] = rd[splitGroupByColumn[i]].ToString();
Response.Write("<br/>COMPARE GROUP [i]==" + compareGroup[i]);
}
compareFlag = 1;
Response.Write("<br/>splitSelectedColumn.LENGTH==" + splitSelectedColumn.Length);
Response.Write("<br/>STACK.LENGTH==" + stackss.Length);
for (int i = 0; i < stackss.Length; i++)
{
stackss[i] = "";
}
for (int i = 0; i < compareGroup.Length; i++)
{
stackss[i] = compareGroup[i];
}
//TESTING PURPOSE ONLY
for (int i = 0; i < stackss.Length; i++)
{
//stack[i] = "";
Response.Write("<br/>STACK.VALUES==" + stackss[i]);
}
var row = dt.NewRow();
DataRowCollection drc = dt.Rows;
DataRow rowss = drc.Add(stackss);
Response.Write("Execute BUTTON");
listBtnOrLbl.Add("button");
}
//stackss = new string[] { "" };
for (int i = 0; i < stackss.Length; i++)
{
stackss[i] = "";
}
int tempValue = 0;
for (int i = 0; i < compareGroup.Length; i++)
{
if (compareGroup[i] == rd[i].ToString())
{
tempValue = tempValue + 1;
if (tempValue == compareGroup.Length)
{
for (int k = 0; k < splitSelectedColumn.Length; k++)
{
stackss[k] = rd[k].ToString();
Response.Write("second rowsssss ==== " + stackss[k]);
if (k + 1 == splitSelectedColumn.Length)
{
var row = dt.NewRow();
DataRowCollection drc = dt.Rows;
DataRow rowss = drc.Add(stackss);
Response.Write("compare flag checking");
Response.Write("Execute LABEL");
listBtnOrLbl.Add("label");
compareFlag = 0;
}
}
}
}
}
//GridView1.DataSource = dt;
//GridView1.DataBind();
}
rd.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Gridview templatefield will generate when user click Refresh button. The above coding is that one to generate column and templatefield
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
Response.Write("<br/>compare flag checking OVER button count=======================" + listBtnOrLbl.Count);
if (e.Row.RowType == DataControlRowType.DataRow)
{
int size = splitGroupByColumn.Length;
//Button[] lnkBtn = new Button[size];
Label[] lblData = new Label[size];
Response.Write("<br/>Inside button count=======================" + listBtnOrLbl.Count);
if ("button".Equals(listBtnOrLbl[j]))
{
for (int i = 0; i < splitGroupByColumn.Length; i++)
{
Button lnkView = new Button();
lnkView.ID = "lnkView";
lnkView.Text = (e.Row.DataItem as DataRowView).Row[splitGroupByColumn[i]].ToString();
//lnkView.Text = (e.Row.DataItem as DataRowView).Row["Id"].ToString();
lnkView.Click += ViewDetails;
lnkView.CommandArgument = (e.Row.DataItem as DataRowView).Row[splitGroupByColumn[i]].ToString();
e.Row.Cells[i].Controls.Add(lnkView);
}
j++;
}
else
{
for (int i = 0; i < splitGroupByColumn.Length; i++)
{
lblData[i] = new Label();
lblData[i].ID = "lblView";
lblData[i].Text = (e.Row.DataItem as DataRowView).Row[splitGroupByColumn[i]].ToString();
Response.Write("<br/>PRINT label==" + lblData[i].Text);
e.Row.Cells[i].Controls.Add(lblData[i]);
//e.Row.Visible = false;
}
j++;
}
}
protected void ViewDetails(object sender, EventArgs e)
{
Response.Redirect("exit.aspx"); //for testing purpose I gave like this, But this method is not calling i think when user clicks button
Response.Write("testing....");
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('TESTING:')", true);
}
Output before user clicks the Button
output1
After clicks the button(first button)
output2
I already did like this before,but that was small one not more complex code like this. that was working fine. Now What i did wrong here?.
Thanks
I think ViewDetails() method is not calling when user clicks the button

Dynamic rows on table c#

two part question:
1:
I am using a session state refresh to hold count of the page reloads but when using a series of if statements the validation isn't working. Code at the bottom. What am I doing wrong?
2:
Using session state against postback doesn't appear to be the most efficient method of doing this, if I added another table with the same functionality, the count would affect both tables.
For example if I only wanted people to be able to add a maximum of three rows to a table, on two tables, they would only be able to add four rows in total.
What would be a better method of storing a count for separate refreshes?
Update
I have found the issue with the code not adding rows to the existing but I'm unsure of how to fix it.
Basically each iteration is deleting the existing row then adding a single row again. So there will never be more than one row.
Any ideas?
namespace FormTest
{
public partial class About : Page
{
protected void Page_Load(object sender, System.EventArgs e)
{
tbl.BorderStyle = BorderStyle.Inset;
tbl.BorderWidth = Unit.Pixel(1);
if (!Page.IsPostBack)
{
Session["count"] = 0;
}
else
{
int count = (int)Session["count"];
count++;
Session["count"] = count;
}
}
protected void cmdCreate_Click(object sender, System.EventArgs e)
{
tbl.Controls.Clear();
int rows = 1;
int cols = 4;
if ((int)Session["count"] == 0)
{
for (int i = 0; i < rows; i++)
{
TableRow rowNew = new TableRow();
tbl.Controls.Add(rowNew);
for (int j = 0; j < cols; j++)
{
TableCell cellNew = new TableCell();
Label lblNew = new Label();
lblNew.Text = "(" + i.ToString() + "," + j.ToString() + ")<br />";
TextBox tbNew = new TextBox();
cellNew.Controls.Add(lblNew);
cellNew.Controls.Add(tbNew);
rowNew.Controls.Add(cellNew);
}
}
}
else
{
if ((int)Session["count"] == 1)
{
for (int i = 0; i < rows; i++)
{
TableRow rowNew = new TableRow();
tbl.Controls.Add(rowNew);
for (int j = 0; j < cols; j++)
{
TableCell cellNew = new TableCell();
Label lblNew = new Label();
lblNew.Text = "(" + i.ToString() + "," + j.ToString() + ")<br />";
TextBox tbNew = new TextBox();
cellNew.Controls.Add(lblNew);
cellNew.Controls.Add(tbNew);
rowNew.Controls.Add(cellNew);
}
}
}
else
{
if ((int)Session["count"] == 2)
{
for (int i = 0; i < rows; i++)
{
TableRow rowNew = new TableRow();
tbl.Controls.Add(rowNew);
for (int j = 0; j < cols; j++)
{
TableCell cellNew = new TableCell();
Label lblNew = new Label();
lblNew.Text = "(" + i.ToString() + "," + j.ToString() + ")<br />";
TextBox tbNew = new TextBox();
cellNew.Controls.Add(lblNew);
cellNew.Controls.Add(tbNew);
rowNew.Controls.Add(cellNew);
}
}
}
else
{
if ((int)Session["count"] == 3)
{
for (int i = 0; i < rows; i++)
{
TableRow rowNew = new TableRow();
tbl.Controls.Add(rowNew);
for (int j = 0; j < cols; j++)
{
TableCell cellNew = new TableCell();
Label lblNew = new Label();
lblNew.Text = "(" + i.ToString() + "," + j.ToString() + ")<br />";
TextBox tbNew = new TextBox();
cellNew.Controls.Add(lblNew);
cellNew.Controls.Add(tbNew);
rowNew.Controls.Add(cellNew);
}
}
}
else
{
Response.Redirect("http://www.google.co.uk");
}
}
}
}
}//end cmdCreate_Click
}
}
You don't need a list of if conditions, you just need to ensure the number of rows is less than your desired limit. You also should store the limit per table to avoid your count clashing if/when more tables are added.
This is how I would do it:
(note: This won't work "as-is" - I've assumed you've removed the code to assign tbl within cmdCreate_Click()and have left it as is for clarity)
namespace FormTest
{
public partial class About : Page
{
private int myFirstTableMaxRows = 3;
protected void Page_Load(object sender, System.EventArgs e)
{
tbl.BorderStyle = BorderStyle.Inset;
tbl.BorderWidth = Unit.Pixel(1);
if (!Page.IsPostBack)
{
Session["myFirstTable_count"] = "0";
}
else
{
int count = (int)Session["myFirstTable_count"];
Session["myFirstTable_count"] = ++count;
}
}
protected void cmdCreate_Click(object sender, System.EventArgs e)
{
tbl.Controls.Clear();
int cols = 4;
int currentRowCount = (int)Session["myFirstTable_count"];
if(currentRowCount <= myFirstTableMaxRows)
{
TableRow rowNew = new TableRow();
tbl.Controls.Add(rowNew);
for (int j = 0; j < cols; j++)
{
TableCell cellNew = new TableCell();
Label lblNew = new Label();
lblNew.Text = "(" + i.ToString() + "," + j.ToString() + ")<br />";
TextBox tbNew = new TextBox();
cellNew.Controls.Add(lblNew);
cellNew.Controls.Add(tbNew);
rowNew.Controls.Add(cellNew);
}
}
else
{
Response.Redirect("http://www.google.co.uk");
}
}//end cmdCreate_Click
}
Update after question edit
The existing rows will go due to this line in the code:
tbl.Controls.Clear();
The table is being cleared, then a single row is added per the logic in the cmdCreate_Click() method.

How to create nested html table in c# using recursion logic?

I just tried over it but i got the HTML tables in the manner of unique,i just need the tables to created one within another.
sample output: http://i.stack.imgur.com/drdXx.jpg][1]sample
In Design Page
<table id="tableContent" border="1" runat="server"></table>
protected void Page_Load(object sender, EventArgs e)
{
var s = 0;
Addtable(s);
}
public void Addtable(int j)
{
HtmlTableRow row = new HtmlTableRow();
HtmlTableCell cell = new HtmlTableCell();
cell.InnerText = "col 1";
row.Cells.Add(cell);
cell = new HtmlTableCell();
cell.InnerText = "col2";
row.Cells.Add(cell);
tableContent.Rows.Add(row);
tableContent.Border =1;
if( j < 5)
{
j++;
Addtable(j);
}
}
You need to change your recursion function as below
public void Addtable(HtmlTable baseTable, int j)
{
HtmlTable innerTable = new HtmlTable();
// change to stylesheet instead. Just added as an example to get the output
baseTable.Style.Add("margin-left", "25px");
baseTable.Style.Add("margin-right", "25px");
baseTable.Style.Add("margin-bottom", "25px");
baseTable.Style.Add("text-align", "center");
baseTable.Border = 1;
//Create a container cell for inner table
HtmlTableRow container = new HtmlTableRow();
HtmlTableCell containerCell = new HtmlTableCell();
Literal l = new Literal();
l.Text = "Table " + j;
containerCell.Controls.Add(l);
containerCell.Controls.Add(innerTable);
containerCell.ColSpan = 2;
container.Cells.Add(containerCell);
baseTable.Rows.Add(container);
if (j < 5)
{
j++;
Addtable(innerTable, j);
}
}
Then call the function
var s = 0;
Addtable(tableContent,s);

Cannot fire runtime radiobutton checkedchanged event inside linkbutton click event

I am trying to fire radiobutton checked changed event on linkbutton click event but instead it goes to the page load and the radiobutton checkedchanged event does not fires.
protected void Page_Load(object sender, EventArgs e)
{
string Query = "select Q101004,Q101005 from Q101 where Q101001<110000013";
DataTable dt = ExecuteDataset(Query).Tables[0];
ViewState["dt"] = dt;
Table t = new Table();
TableRow r = new TableRow();
t.Rows.Add(r);
TableCell c = new TableCell();
lnkbtn = new LinkButton();
r.Cells.Add(c);
lnkbtn.Text = "Click Here";
lnkbtn.Visible = true;
lnkbtn.CommandName = "Test";
lnkbtn.CommandArgument = "Hi";
lnkbtn.ID = "Hi";
PlaceHolder2.Controls.Add(lnkbtn);
for (int i = 0; i < dt.Rows.Count; i++)
{
rb = new RadioButton();
rb.AutoPostBack = true;
rb.ID = "m" +i;
rb.GroupName = "a";
rb.Text = dt.Rows[0][0].ToString();
CbxList = new CheckBoxList();
CbxList.ID = "Cbx"+i;
CbxList.Enabled = false;
CbxList.RepeatDirection = RepeatDirection.Horizontal;
CbxList.RepeatColumns = 2;
CbxList.CellPadding = 10;
CbxList.CellSpacing = 5;
CbxList.RepeatLayout = RepeatLayout.Table;
options = dt.Rows[0][1].ToString().Split('~');
PlaceHolder2.Controls.Add(new LiteralControl("<br/>"));
for (int j = 0; j < options.Length; j++)
{
CbxList.Items.Add(new ListItem(options[j], options[j]));
}
PlaceHolder2.Controls.Add(rb);
PlaceHolder2.Controls.Add(CbxList);
if (i ==0)
rb.CheckedChanged += new EventHandler(rb_CheckedChanged);
else
lnkbtn.Click += new EventHandler(lnkbtn_Click);
}
}
void lnkbtn_Click(object sender, EventArgs e)
{
DataTable dt = (DataTable)ViewState["dt"];
lnkbtn = (LinkButton)PlaceHolder2.FindControl("Hi");
string str=((LinkButton)sender).CommandArgument;
//lnkbtn.Enabled = true;
if (lnkbtn.ID == str)
{
rb = new RadioButton();
rb.AutoPostBack = true;
rb.ID = "m";
rb.GroupName = "a";
rb.Text = dt.Rows[0][0].ToString();
CbxList = new CheckBoxList();
CbxList.ID = "Cbx";
CbxList.Enabled = false;
CbxList.RepeatDirection = RepeatDirection.Horizontal;
CbxList.RepeatColumns = 2;
CbxList.CellPadding = 10;
CbxList.CellSpacing = 5;
CbxList.RepeatLayout = RepeatLayout.Table;
options = dt.Rows[0][1].ToString().Split('~');
PlaceHolder2.Controls.Add(new LiteralControl("<br/>"));
for (int i = 0; i < options.Length; i++)
{
CbxList.Items.Add(new ListItem(options[i], options[i]));
}
PlaceHolder2.Controls.Add(rb);
PlaceHolder2.Controls.Add(CbxList);
if (lnkbtn.CommandName == "Test")
{
rb.CheckedChanged += new EventHandler(rb_CheckedChanged);
}
}
}
Your code subscribes to the checked changed but does not invoke it.
If you want to do this, you could call the rb_CheckedChanged() method directly.
hope this helps....its working fine for me.
Just Modify your code with this code and You will be able to achieve your desired output
private void InitPage()
{
string a1, b,a2,b2;
_objSession = (ClsSession)Session["Login"];
ds = _objSession._DataSet;
dtAll = ds.Tables[3];
dr = dtAll.NewRow();
string str2 = (string)ViewState["str1"];
if (str2 != null)
{
string[] str3 = str2.Split('~');
a2 = str3[0];
b2 = str3[1];
}
else
{
a2 = "a0";
b2 = "b0";
}
str = (string)ViewState["str"];
if (str == null)
{
a1 = "a0";
b = "b";
}
else
{
string[] str1 = str.Split('~');
a1 = str1[0];
b = str1[1];
}
if (str==null)
{
for (int j = 0; j < dtAll.Rows.Count; j++)
{
Table t = new Table();
TableRow r = new TableRow();
t.Rows.Add(r);
TableCell c = new TableCell();
lnkbtn = new LinkButton();
r.Cells.Add(c);
lnkbtn.Text = (j + 1).ToString();
lnkbtn.Visible = true;
lnkbtn.CommandName = "Test";
lnkbtn.CommandArgument = "Hi" + j;
lnkbtn.ID = "Hi" + j;
lnkbtn.ForeColor = Color.Blue;
lnkbtn.Width = 30;
lnkbtn.Font.Bold = true;
lnkbtn.Font.Size = 14;
lnkbtn.Font.Underline = false;
lnkbtn.Click += new EventHandler(lnkbtn_Click);
c.Controls.Add(lnkbtn);
plcHdrLinkButton.Controls.Add(lnkbtn);
}
ViewState["a"] = 0;
}
if (str2 != null)
{
string[] str3 = str2.Split('~');
a2 = str3[0];
a1 = a2;
}
string resultString = Regex.Match(a1, #"\d+").Value;
int a = int.Parse(resultString);
ViewState["a"] = a;
plcHdrQuestion.Controls.Clear();
rb = new RadioButton();
rb.ID = "m" + a;
rb.AutoPostBack = true;
rb.GroupName = "a";
rb.Text = (a + 1) + "." + " " + dtAll.Rows[a][4].ToString();
CbxList = new CheckBoxList();
CbxList.ID = "Cbx" + a;
CbxList.Enabled = false;
CbxList.RepeatDirection = RepeatDirection.Horizontal;
CbxList.RepeatColumns = 2;
CbxList.CellPadding = 10;
CbxList.CellSpacing = 5;
CbxList.RepeatLayout = RepeatLayout.Table;
options = dtAll.Rows[a][5].ToString().Split('~');
plcHdrQuestion.Controls.Add(new LiteralControl("<br/>"));
for (int i = 0; i < options.Length; i++)
{
CbxList.Items.Add(new ListItem(options[i], options[i]));
}
plcHdrQuestion.Controls.Add(rb);
plcHdrQuestion.Controls.Add(CbxList);
rb.CheckedChanged += new EventHandler(lnkbtn_Click);
string st = (string)ViewState["str"];
ViewState["str1"] = st;
ViewState["str"] = null;
}
protected void lnkbtn_Click(object sender, EventArgs e)
{
Boolean _flag=true;
ds = _objSession._DataSet;
dt1 = ds.Tables[3];
dr = dt1.NewRow();
StringBuilder sb=new StringBuilder ();
for (int i = 0; i < dt1.Rows.Count; i++)
{
Cbx = (RadioButton)plcHdrQuestion.FindControl("m" + i);
Cbx1 = (CheckBoxList)plcHdrQuestion.FindControl("Cbx" + i);
if (Cbx != null)
{
if (Cbx.Checked == true)
{
Cbx1.Enabled = true;
_flag = false;
string st1 = (string)ViewState["st"];
string st="c";
if (st1 != null)
st = st1 + "~" + st;
ViewState["st"] = st;
st1 = (string)ViewState["st"];
sb.Append(st);
}
break;
}
}
int count=(sb.ToString().Count());
if (count>2)
{
_flag = true;
}
if ((lnkbtn.CommandName == "Test") && (_flag ==true))
{
for (int j = 0; j < dt1.Rows.Count; j++)
{
lnkbtn = (LinkButton)plcHdrLinkButton.FindControl("Hi" + j);
string str = ((LinkButton)sender).CommandArgument;
lnkbtn.Enabled = true;
if (lnkbtn.ID == str)
{
ViewState["str"] = str + "~" + lnkbtn.ID;
InitPage();
ViewState["st"] = null;
_flag = false;
break;
}
}
}
}
You need to read up on your ASP.NET Page Life Cycle - http://msdn.microsoft.com/en-us/library/ms178472(VS.100).aspx
Very roughly, the following events get called during page lifecycle.
Init -> Controls are created & wired up with event handlers
Load ViewState/ControlState -> Controls are reset to their previous state from the last round trip (including whether or not they need to fire their events)
Load -> Controls are loaded into the Page's Control Tree
Control Events (Clicks etc...) are executed.
The problem you have is that you are creating your control and wiring it up to fire dynamically in the 4th step there, which is too late in the page lifecycle.
On the next round trip, if someone does interact with that control, and the lifecycle starts over, that control won't exist by the time the page is preparing to execute commands.
You'll need to move the creation of your RadioButton to a much earlier stage in the pages creation. In your updated code, try moving your Page_Load code into the override oninit method instead.

Display pictures with their name from database in winforms?

dataGridView1.DataSource = null;
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand mySqlCommand = new SqlCommand("Select Name, Picture from Employee ", myDatabaseConnection))
{
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(mySqlCommand);
adapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
}
Instead of using datagridview, How I can display the picture with their Name in the panel or other control from the database something like this format http://static.neatorama.com/images/2008-04/yearbook-project-robot-johnny.gif in win form?
For example I have 7 records in the database, the form will display 7 panels with picture and label. And when I click or select a panel it will dipslay more information such as Address, Contacts, Etc in a textBox. If the records in the database is too many to fit in the form there will be a vertical or horizontal scroll bar.
I suggest you to create the objects you need dynamically. You can use "Location" to position your object.
Example :
int cptx = 0;
int cpty = 0;
for(int i=0; i<ds.Tables[0].Rows.Count;i++)
{
PictureBox currentpic = new PictureBox();
Label currentlabel = new Label();
currentpic.Size = new Size(20,20);
currentlabel.Size = new Size(20,20);
currentpic.BorderStyle = BorderStyle.FixedSingle;
currentlabel.Text = "te";
if(cptx >= 4)
{
cptx = 0;
cpty ++;
}
currentpic.Location= new Point((cptx*25),(cpty*50));
currentlabel.Location = new Point((cptx*25),(cpty*50)+25);
This.Controls.Add(currentpic);
cptx ++;
}
This code should do this :
EDIT : I suggest you to take a look at the "User control", the user control allow you to create you own control. So, the picture and the label will be inside a single control. The advantage to use the user control is the control you will create will be totally reusable for your other windows and/or programs.
Form has only one panel (pnlGrid) and panel's AutoScroll property setted as true;
DataTable dtImage = new DataTable();
dtImage.Columns.Add("Path");
dtImage.Columns.Add("Name");
dtImage.Rows.Add(new object[] { "ImagePath", "ImageText" });
dtImage.Rows.Add(new object[] { "ImagePath", "ImageText" });
dtImage.Rows.Add(new object[] { "ImagePath", "ImageText" });
CreateImageGrid(dtImage);
and method;
private void CreateImageGrid(DataTable dtDataSource)
{
int colCount = 5;
int rowCount = 0;
int imgWidth = 100;
int imgHeight = 100;
int imgPadding = 10;
int lblPadding = 5;
int ind = -1;
PictureBox pic = null;
Label lbl = null;
if (dtDataSource.Rows.Count > colCount)
{
rowCount = Convert.ToInt32(dtDataSource.Rows.Count / colCount);
if (Convert.ToInt32(dtDataSource.Rows.Count % colCount) > 0)
{
rowCount++;
}
}
else
{
rowCount = 1;
}
for (int j = 0; j < rowCount; j++)
{
for (int i = 0; i < colCount && dtDataSource.Rows.Count > ((j * colCount) + i); i++)
{
ind = (j * colCount) + i;
pic = new PictureBox();
pic.Image = Image.FromFile(dtDataSource.Rows[ind]["Path"].ToString());
pnlGrid.Controls.Add(pic);
pic.Width = imgWidth;
pic.Height = imgHeight;
pic.Top = (j * (imgHeight + imgPadding)) + imgPadding;
pic.Left = (i * (imgWidth + imgPadding)) + imgPadding;
lbl = new Label();
lbl.Text = dtDataSource.Rows[ind]["Name"].ToString();
pnlGrid.Controls.Add(lbl);
lbl.Left = pic.Left;
lbl.Top = pic.Top + pic.Height + lblPadding;
}
}
}
Note: Text lengths may cause problems, you should define some rules.

Categories