generate Dynamic Checkbox in ASP.Net - asp.net

plz tell me whats wrong in code bcz i m not able to add control on page. i m getting the values right & if i just CheckBoxList2.Items.Add(row["subj_nme"].ToString()); the check box get created
if (ds.Tables.Count > 0)
{
foreach (DataRow row in ds.Tables[0].Rows)
{
chkList1 = new CheckBox();
chkList1.Text = row["subj_nme"].ToString();
chkList1.ID = row["subjid"].ToString();
chkList1.Checked = true;
chkList1.Font.Name = "Verdana";
chkList1.Font.Size = 12;
CheckBoxList2.Controls.Add(chkList1);
}
}

I think you can use this code for binding your CheckBoxList2 to DataTable as follow.
CheckBoxList2.DataSource = ds.Tables[0];
CheckBoxList2.DataTextField = "subj_nme";
CheckBoxList2.DataValueField = "subjid";
CheckBoxList2.DataBind();
CheckBoxList2.Font.Name = "Verdana";
CheckBoxList2.Font.Size = 12;
To check them all you can do this
for(int i=0;i<CheckBoxList2.Items.Count;i++)
{
CheckBoxList2.Items[i].Selected = true;
}

Related

can't add all the selected rows to the dataset

I have added records chosen (checkbox) in a datatable shown below, records have been displaying in a datagrid populated using stored procedure. Then on the button click I save all the selected (added) records to the ds in database.
public DataSet getMain()
{
DataSet ds = CFObj.GetSchemaRequest();
DataRow dr;
dr = ds.Tables[0].NewRow();
for (int i = 0; i < dgAvailableCandidates.Items.Count; i++)
{
CheckBox saveChkBoxItem = (CheckBox)dgAvailableCandidates.Items[i].FindControl("chkbox_SelectCandidate");
if (saveChkBoxItem.Checked)
{
//ds.Tables[0].Columns["pk_scrndRecId"].ReadOnly = false;
dr["pk_scrndRecId"] = "0";
dr["fk_jobId"] = ddl_jobList.SelectedValue.ToString();
obj._fkjob_Id = ddl_jobList.SelectedValue.ToString();
dr["fk_recId"] = dgAvailableCandidates.DataKeys[i].ToString();
obj._fk_recId = dgAvailableCandidates.DataKeys[i].ToString();
}
}
ds.Tables[0].Rows.Add(dr);
return ds;
}
here my issue is when ds.Tables[0].Rows.Add(dr); i put outside of loop, it adds only one last selected record to ds, and when I put this inside loop, it throws following exception
[pk_scrndRecId] column is read only
and when I have placed this inside if block, it throws following exception:
This row already belongs to this table.
I am not able to understand why this code doesn't add all the selected rows of datagrid to the ds.
please help. thanks!
You have to create a new row and add it to datatable inside the loop and so each time it will create a new instance and add it to your datatable.
Check updated code.
public DataSet getMain()
{
DataSet ds = CFObj.GetSchemaRequest();
DataRow dr;
for (int i = 0; i < dgAvailableCandidates.Items.Count; i++)
{
CheckBox saveChkBoxItem = (CheckBox)dgAvailableCandidates.Items[i].FindControl("chkbox_SelectCandidate");
if (saveChkBoxItem.Checked)
{
dr = ds.Tables[0].NewRow();
//ds.Tables[0].Columns["pk_scrndRecId"].ReadOnly = false;
dr["pk_scrndRecId"] = "0";
dr["fk_jobId"] = ddl_jobList.SelectedValue.ToString();
obj._fkjob_Id = ddl_jobList.SelectedValue.ToString();
dr["fk_recId"] = dgAvailableCandidates.DataKeys[i].ToString();
obj._fk_recId = dgAvailableCandidates.DataKeys[i].ToString();
ds.Tables[0].Rows.Add(dr);
}
}
return ds;
}

Database driven menu is too slow

in ASP.Net using C#, I am populating an ASP.Net menu control from database dynamically. I am trying to make those items unusable which have some child items below them. This is to ensure that on mobile, where we dont have a mouse to hover, on clicking the parent menu item, user will surely get child items in stead of a postback. The code below is working fine but with a drawback, it takes too much time to load and in the mean time shows a bad result by displaying all the items (all parent + all child) vertically in a single view.
SqlCommand com = new SqlCommand("SELECT * FROM menutab order by sno", c.con);
if(c.con.State == ConnectionState.Closed)
c.con.Open();
da = new SqlDataAdapter(com);
table = new DataTable();
da.Fill(table);
parents = new int[table.Rows.Count];
for (int i = 0; i < table.Rows.Count; i++)
if (table.Rows[i].ItemArray.GetValue(2).ToString() != String.Empty)
parents[i] = Convert.ToInt32(table.Rows[i].ItemArray.GetValue(2).ToString());
DataRow[] drowpar = table.Select("menu_parent = " + 0);
view = new DataView(table);
view.RowFilter = "menu_parent is NULL";
foreach (DataRowView row in view)
{
MenuItem menuItem = new MenuItem(row["item"].ToString(), row["sno"].ToString());
//menuItem.NavigateUrl = row["menu_url"].ToString();
for (int i = 0; i < parents.Length; i++)
{
if (Convert.ToInt32(row["sno"].ToString()) == parents[i])
{
menuItem.Selectable = false;
}
}
NavigationMenu.Items.Add(menuItem);
AddChildItems(table, menuItem);
}
private void AddChildItems(DataTable table, MenuItem menuItem)
{
DataView viewItem = new DataView(table);
viewItem.RowFilter = "menu_parent=" + menuItem.Value;
foreach (DataRowView childView in viewItem)
{
MenuItem childItem = new MenuItem(childView["item"].ToString(), childView["sno"].ToString());
//childItem.NavigateUrl = childView["menu_url"].ToString();
for (int i = 0; i<parents.Length; i++)
{
if (Convert.ToInt32(childView["sno"].ToString()) == parents[i])
{
childItem.Selectable = false;
}
}
menuItem.ChildItems.Add(childItem);
AddChildItems(table, childItem);
}
}
Can this process be more faster and reliable with some other code implementation?
Database driven menu will surely show some lag in loading it for the first time and it depends on the speed of your web server too. However, the following code will help you in reducing the load time:
DataRow[] drowpar = table.Select("menu_parent = " + 0);
foreach (DataRow row in drowpar)
{
MenuItem menuItem = new MenuItem(row["item"].ToString(), row["sno"].ToString());
NavigationMenu.Items.Add(menuItem);
AddChildItems(table, menuItem);
}
private void AddChildItems(DataTable table, MenuItem menuItem)
{
DataView viewItem = new DataView(table);
viewItem.RowFilter = "menu_parent=" + menuItem.Value;
foreach (DataRowView childView in viewItem)
{
MenuItem childItem = new MenuItem(childView["item"].ToString(), childView["sno"].ToString());
menuItem.Selectable = false;
menuItem.ChildItems.Add(childItem);
AddChildItems(table, childItem);
}
}
If you are doing other tasks on page_load, make sure you write the menu code at beginning so that server starts the processing with menu and then works on other code.
Hope this helps.

How can itereate through checkboxes using forlopp in C#?

I need to check whether the checkbox values are ticked or not using 'for' loop.
CheckBox chkBox = (CheckBox)tab_patients.Controls[chk + i];
from searches i got this line. what this tab_patients denote ?`
string chk = "CheckBox";
for (int i = 1; i < 13; i++)
{
for (int k = 1; k < 4; k++)
{
// CheckBox chkBox = (CheckBox)tab_patients.Controls[chk + i];
CheckBox cb = (CheckBox)this.Page.Form.FindControl("chk"+i.ToString());
if(cb.Checked==true)
{
check = i + "0" + k;
}
}}
Make your life easier and create the checkboxes with checkboxlists: http://msdn.microsoft.com/de-de/library/system.web.ui.webcontrols.checkboxlist.aspx
<asp:CheckBoxList ID="SomeElement" runat="server"
AutoPostBack="true"
RepeatColumns="4"
EnableViewState="true">
</asp:CheckBoxList>
With the Repeatcolumns property you are telling the element, that you infact want 4 columns, so the control will devide your 32 elements by 4 and group those checkboxes by the pack of 8.
After this, you can iterate through every list like this:
foreach(var cb in checkboxlistID)
{
if(cb.Checked)
{
//do something
}
}
On top of that, here is some old code showing you how to fill a checkboxlist with data fetched from a SQL-query. You can ignore the if expression, which is checking if there is cached data, from which to fill all the checkboxes.
using (OleDbConnection connection = new OleDbConnection(ConfigurationManager.ConnectionStrings["database"].ConnectionString))
{
string Query = #"SELECT * from level";
OleDbCommand command = new OleDbCommand(Query, connection);
if (Session["SavedLevelItems"] != null)
{
CheckBoxListLevel.Items.Clear();
List<ListItem> SessionList = (List<ListItem>)Session["SavedLevelItems"];
foreach (var item in SessionList)
{
try
{
CheckBoxListLevel.Items.Add(item);
}
catch { }
}
}
else
{
connection.Open();
CheckBoxListLevel.DataTextField = "bez_level";
CheckBoxListLevel.DataValueField = "id_level";
OleDbDataReader ListReader = command.ExecuteReader();
CheckBoxListLevel.DataSource = ListReader;
CheckBoxListLevel.DataBind();
ListReader.Close(); ListReader.Dispose();
}
}

Build Treeview with parent, child tables

I am building treeview using asp.net 2.0/3.5 from master detail table.
ParentTable Value
---ChildTable Value
---GrandChildTable1 Node
---GrandChildTable1 Value
---GrandChildTable2 Node
---GrandChildTable1 Value
I have created something like this to populate node values. But I am not sure how to display GrandChildNode and values. Could you please let me know if there are any ideas?
Thank you for any help.
protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
{
switch (e.Node.Depth)
{
case 0:
GetParentTableValues(e.Node);
break;
case 1:
GetChildTableValues(e.Node);
break;
case 2:
}
}
Here is my solution:
string NodeText = string.Empty;
string NodeKey = string.Empty;
TreeRolesList.Nodes.Clear();
DataTable dtEnqRoles = bllENQRolesMaster.GetENQRolesMasterByRolesDetail();
if (dtEnqRoles.Rows.Count > 0)
{
for (int i = 0; i < dtEnqRoles.Rows.Count; )
{
NodeText = dtEnqRoles.Rows[i]["RoleDescriptionMaster"].ToString().Trim();
NodeKey = dtEnqRoles.Rows[i]["RoleMasterID"].ToString();
TreeNode pNode = new TreeNode(NodeText, NodeKey);
TreeRolesList.Nodes.Add(pNode);
foreach (DataRow dr in dtEnqRoles.Select("RoleMasterID = " + NodeKey))
{
TreeNode childNode = new TreeNode(dr["RoleDescriptionDetail"].ToString().Trim(), dr["RoleDetailID"].ToString());
pNode.ChildNodes.Add(childNode);
i++; //incrementing the outer loop here
}
}
TreeRolesList.ExpandAll();
}

Dynamically add checkboxlist into placeholder and get the checked value of the checkboxlist

I am creating an admin Page, in which checkboxlist(User list from DB)is to be created dynamically and its the checked users value is retrieved.
There are different types of users, so it is distinguised groupwise.
Now first a panel is defined, the checkboxlist is created dynamically and placed inside the panel, then the panel is placed inside a Placeholder.
What Iam doing here is placing the checkboxlist inside the panel, then the panel inside the placeholder. So the values of the Checkboxlist is not retrieved, due to the panel it doesnt get the checkboxlist and it doesn't loop through the Checkboxlist.
What I have done is.
private void AddControl(string pUserGrp, int pUserGrp_Id, int pName)
{
CheckBoxList chkList = new CheckBoxList();
CheckBox chk = new CheckBox();
User us = new User();
us.OrderBy = "Order By User_Name";
us.WhereClause = "Where UserRole_Id = " + pUserGrp_Id ;
chkList.ID = "ChkUser" + pName ;
chkList.AutoPostBack = true;
chkList.Attributes.Add("onClick", "getVal(ChkUser" + pName + ");");
chkList.RepeatColumns = 6;
chkList.DataSource = us.GetUserDS();
chkList.DataTextField = "User_Name";
chkList.DataValueField = "User_Id";
chkList.DataBind();
chkList.Attributes.Add("onClick", "getVal(this);");
Panel pUser = new Panel();
if (pUserGrp != "")
{
pUser.GroupingText = pUserGrp ;
chk.Text = pUserGrp;
}
else
{
pUser.GroupingText = "Non Assigned Group";
chk.Text = "Non Assigned group";
}
pUser.Controls.Add(chk);
pUser.Controls.Add(chkList);
Place.Controls.Add(pUser);
}
private void setChecked(int pPageGroupId)
{
ArrayList arr = new ArrayList();
PageMaster obj = new PageMaster();
obj.WhereClause = " Where PageGroup_Id = " + pPageGroupId;
arr = obj.GetPageGroupUserRights(null);
CheckBoxList chkList = (CheckBoxList)Place.FindControl("ChkUser");
if (chkList != null)
{
for (int i = 0; i < chkList.Items.Count; i++)
{
if (arr.Count > 0)
{
int ii = 0;
while (ii < arr.Count)
{
PageMaster oCand = (PageMaster)arr[ii];
if (oCand.User_Name == chkList.Items[i].Text)
{
if (!chkList.Items[i].Selected)
{
chkList.Items[i].Selected = true;
}
}
ii++;
oCand = null;
}
}
}
}
}
public string GetListCheckBoxText()
{
StringBuilder sbtext = new StringBuilder();
foreach (Control c in Place.Controls)
{
if (c.GetType().Name == "CheckBoxList")
{
CheckBoxList cbx1 = (CheckBoxList)c;
foreach (ListItem li in cbx1.Items)
{
if (li.Selected == true)
{
sbtext.Append(",");
sbtext.Append(li.Value);
}
else
{
sbtext.Append(li.Value);
}
}
}
}
return sbtext.ToString(); }
It doesnt get through the Checkboxlist control in the setChecked(), also doesnt loop through the GetListCheckBoxTest().
Anyone can plz help me.
Regards
The problem is that you are trying to find a control (in setChecked) without setting the Name property. You are using this:
CheckBoxList chkList = (CheckBoxList)Place.FindControl("ChkUser");
But where is this in AddControl?
chkList.Name = "ChkUser";
And in GetListCheckBoxText instead of...
if (c.GetType().Name == "CheckBoxList")
...use this:
if (c.GetType()== typeof(CheckBoxList))

Resources