CheckBoxList1_SelectedIndexChanged does not get fired - asp.net

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(',');

Related

how to checked checkbox list using database

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.

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

how to check items in checkboxlist?

i have a checkboxlist that i want to check some of it's items,
items that i wanna check store in database, i'm selecting them from database and in a loop i wrote thees but just last item selected :(( :
var selectedRoles = (from r in DataContext.Context.Core_PagesPermission
where r.PageName.Contains(pageName) select r)
.FirstOrDefault();
if(selectedRoles != null)
{
string roles = selectedRoles.Roles;
string[] role = roles.Split(',');
int countTags = role.Count();
foreach (string word in role)
{
CheckBoxList1.SelectedValue = word;
Response.Write(word + "<br/>");
countTags -= 1;
}
}
this worked :
var selectedRoles = (from r in DataContext.Context.Core_PagesPermission where r.PageName.Contains(pageName) select r)
.FirstOrDefault();
dsRoles.DataBind();
CheckBoxList1.DataBind();
if(selectedRoles != null)
{
string roles = selectedRoles.Roles;
string[] role = roles.Split(',');
foreach (string word in role)
{
try
{
CheckBoxList1.Items.FindByValue(word).Selected = true;
}
catch (Exception exp)
{
lbError.Text= exp.ToString();
}
You will want to select the individual items:
CheckBoxList1.Items.FindByText(word).Selected = true;
or
CheckBoxList1.Items.FindByValue(word).Selected = true;
However, if the checkboxlist doesn't have the text/value you are looking for, it will throw an error.
datatable method checkboxlist
for (int i = 0; i < dt.Rows.Count; i++)
{
chkCategories.Items.FindByValue(dt.Rows[i]["CategoryID"].ToString()).Selected = true;
}

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";

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