how to checked checkbox list using database - asp.net

I have CheckBoxList and want to checked it on edit button. if the column in database has value it will checked otherwise unchecked. checkbox list values are from database.
It show the error:
Index was out of range. Must be non-negative and less than the size of the collection.
While debugging on:
Chk_seat.Items[j].Selected = true;
How can I do that?
Here is my code:
<asp:CheckBoxList ID="Chk_seat" runat="server" RepeatDirection="Horizontal">
</asp:CheckBoxList>
public void updatefields_seat(long CarID)
{
SqlConnection cn = new SqlConnection(connection);
string qry = #"SELECT [ID]
,[ReferenceID]
,[CarID]
,[Child-Seat]
,[Leather-Seat]
,[Power-Seat]
,[Navigation-System]
,[Power-Steering]
,[Bucket-Seat]
,[IsActive]
FROM [dbo].[Seat_tbl] Where CarID=" + CarID + "";
DataSet dsSeat = new DataSet();
dsSeat = cm.GetQryInDataset(qry);
if (dsSeat.Tables.Count > 0)
{
for (int i = 0; i < dsSeat.Tables[0].Rows.Count; i++)
{
for (int j = 0; j < dsSeat.Tables[0].Columns.Count; j++)
{
if (dsSeat.Tables[0].Rows[i]["Child-Seat"].ToString() != "")
{
Chk_seat.Items[j].Selected = true;
}
}
}
}
}

dsSeat.Tables[0].Columns.Count could be greater than the size/length of your CheckBoxList that's why you are getting this error:
Index was out of range. Must be non-negative and less than the size of the collection.

Related

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();
}
}

CheckBoxList1_SelectedIndexChanged does not get fired

I have checkboxlist. User is able to check multiple checkboxes.I want to fetch
checkboxe's text.So I wrote like this.But my event(CheckBoxList1_SelectedIndexChanged) does not get fire.I already made checkboxlist's autopostback = "true".
string str = string.Empty;
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
if (CheckBoxList1.Items[i].Selected)
{
str = CheckBoxList1.Items[i].Text;
str = str +',';
}
}
str = str.TrimEnd(',');

Multiple Textbox values into database

I have multiple textboxes in my form like txtTask0, txtTask1... txtTask12.
so I want to pass values of those textboxes into my webservice one by one.
for (int i = 0; i <= 12 ; i++)
{
sOUT = ws_service.InsertAchievement(i,txtTask0.Text,txtAchieve0.Text);
}
Here instead of passing txtTask0.text I need to pass the "i" value one by one like
txtTask[i].text
something similar to this
TextBox tb = (TextBox) Controls["txtTask" + i];
from this link
But that code results in error like
Error 92 The best overloaded method match for 'System.Web.UI.ControlCollection.this[int]' has some invalid arguments
How can I pass multiple textbox values into the loop.?
You cant do like that, because the Controls[index] expects an integer as its parameter, but you are passing a "string concatenated with an integer" it wont work, instead you do like below it will work, hope it will help you...
foreach (Control c in this.Controls)
{
int i = 0;
if (c is TextBox)
{
while(i < 10)
{
if (c.Name == "txtTask" + i)
{
MessageBox.Show("This is textBox" + i);
}
i++;
}
}
}
EDIT :
If the condition if(c is TextBox) is not parsing correctly then do like
foreach (Control c in this.Controls)
{
int i = 0;
while (i < this.Controls.Count)
{
if (c.Name == "txtTask" + i)
{
MessageBox.Show("This is textBox" + i);
}
i++;
}
}
EDIT 2:
Or Simply if you want to loop out in all textbox controls in aspx page use this following code part. It works very perfectly..
int count = 0;
foreach (Control c in this.Page.Controls)
{
foreach (Control c1 in c.Controls)
{
int i = 0;
if (c1 is TextBox)
{
while (i < 10)
{
if (c1.ID == "TextBox" + i)
{
count++;
}
i++;
}
}
}
}
Label1.Text = count + " textbox(es) has been found";

Setting the "Selected" property of an ASP.NET ListItem (HTML Generic Control)

For reasons outside my control I have a table containing input and select fields built using regular HTML with the runat="server" attribute (as opposed to standard ASP.NET controls). I am trying to set a value to be selected when the page is loaded based on values being passed from the Session (again, factor outside my control).
Setting the Selected property of the list item does nothing and doesn't select the item in question. How do I achieve this?
The code is basically this (names generic-ized):
HtmlSelect dropdownList = ((HtmlSelect)myTable.Rows[0].Cells[5].FindControl("DropdownList");
DataSet allListItems = this.GetDefaultListItems();
foreach (DataRow row in allListItems.Tables[0].Rows)
{
ListItem li = new ListItem(row["TextField"].ToString(), row["ValueField"].ToString());
if (li.Text == selectedListItemText)
{
li.Selected = true;
}
dropdownList.Items.Add(li);
}
the Select portion doesn't work, although it gets executed on the proper item. Should this code be called in a specific event? I believe it's being called in Page_Load; should it be called in Pre_Render instead?
EDIT 03/09/2011: Well, I don't know how I fixed it but it's working now. So... yeah.
Try:
foreach (DataRow row in allListItems.Tables[0].Rows)
{
ListItem li = new ListItem(row["TextField"].ToString(), row["ValueField"].ToString());
dropdownList.Items.Add(li);
if (li.Text == selectedListItemText)
{
dropdownList.SelectedIndex = dropdownList.Items.Count-1;
}
}
edit
Source for get SelectedIndex in HtmlSelect:
get {
for (int i = 0; i < this.Items.Count; i++)
{
if (this.Items[i].Selected)
{
return i;
}
}
}
...
set {
...
if (value >= 0)
{
this.Items[value].Selected = true;
}
}
Meaning... it should be functionally identical to set the Selected property for a single ListItem at any time, so my suggestion is functionally identical to the original.
So, suspect: data problem, e.g. more than one item marked as selected? Lifecycle problem (created control at wrong time?)
This is my working test-code, now, what`s the difference to yours?
aspx:
<table id="myTable" runat="server">
<tr>
<td> </td><td> </td><td> </td><td> </td><td>Dropdown:</td><td><select id="DropdownList" runat="server"></select></td>
</tr>
</table>
codebehind:
private string selectedListItemText {
get {
if (Session("selectedListItemText") == null) {
Session("selectedListItemText") = "7. row";
}
return Session("selectedListItemText").ToString;
}
set { Session("selectedListItemText") = value; }
}
protected void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack) {
HtmlSelect dropdownList = (HtmlSelect)myTable.Rows(0).Cells(5).FindControl("DropdownList");
DataSet allListItems = this.GetDefaultListItems();
foreach (DataRow row in allListItems.Tables[0].Rows) {
ListItem li = new ListItem(row["TextField"].ToString(), row["ValueField"].ToString());
if (li.Text == selectedListItemText) {
li.Selected = true;
}
dropdownList.Items.Add(li);
}
}
}
private DataSet GetDefaultListItems()
{
DataSet ds = new DataSet();
DataTable tbl = new DataTable();
ds.Tables.Add(tbl);
tbl.Columns.Add("ValueField");
tbl.Columns.Add("TextField");
for (Int32 i = 1; i <= 10; i++) {
DataRow row = tbl.NewRow();
row["ValueField"] = i;
row["TextField"] = i + ". row";
tbl.Rows.Add(row);
}
return ds;
}
[converted from VB.Net to C#]

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