How can itereate through checkboxes using forlopp in C#? - asp.net

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

Related

Why Itemscontrol is inconsistent with item source in datagrid wpf?

When First time I open the form, datagrid shows data but when I open other form and again open this form this it gives error Itemscontrol is inconsistent with item source
This is my Datagrid in which is used to bind the list.
```
<DataGrid.Columns>
<DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTextColumn Header="Description" Binding="{Binding Description}" Foreground="Black" IsReadOnly="True" />
</DataGrid.Columns>
</DataGrid>```
here on form load function , the datagrid loads.
{
// dtGrid1.Items.Clear();
DataTable dt_Grup = new DataTable();
DataTable dt_Type = new DataTable();
try
{
dt_Grup = dal.Select();
for(int i=0; i< dt_Grup.Rows.Count; i++)
{
FeeGroupControlShowBLL ck = new FeeGroupControlShowBLL();
dt_Type = dal.Select1("SELECT tblFeeType.Fee_Type_Name, tblFeeTypeGroup.Amount from tblFeeTypeGroup inner join tblFeeType on tblFeeTypeGroup.Fee_TypeID = tblFeeType.Fee_Type_ID where Fee_GroupID = '" + dt_Grup.Rows[i][0].ToString() + "'");
ck.groupName = dt_Grup.Rows[i][1].ToString();
ck.Description = dt_Grup.Rows[i][2].ToString();
for (int j = 0; j < dt_Type.Rows.Count; j++)
{
string Type_Amount = (string)dt_Type.Rows[j][0] + " Rs" +(string)dt_Type.Rows[j][1];
ck.FeeTypeName.Add(Type_Amount);
}
b.Add(ck);
}
dtGrid1.ItemsSource = b;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
db.con.Close();
}
}```

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.

dynamic data binding gridview

my datatable formed as follows
DataTable dtFinalData = new DataTable();
//Adding columns for BR details
dtFinalData.Columns.Add("SupId", typeof(string));
dtFinalData.Columns.Add("SupName", typeof(string));
DateTime dt = DateTime.Today;
int num = DateTime.DaysInMonth(DateTime.Today.Year, DateTime.Today.Month);
//--> adding columns for date part (1-31)
for (int i = 1; i < num + 1; i++)
{
dtFinalData.Columns.Add(i.ToString(), typeof(bool));
}
//<-- adding columns for date part (1-31)
#endregion
#region Fill dtFinalData
//--> Looping each BR from tblBrList
foreach (DataRow BrRow in dtBrList.Rows)
{
DataRow dr = dtFinalData.NewRow();
int SupId = Convert.ToInt32(BrRow[0]); //retrieve BR ID from dtBrList
String supName = BrRow[1].ToString(); //retreive Supervisor name from dtBrList
dr["SupId"] = SupId.ToString();
dr["SupName"] = supName;
for (int i = 1; i < num + 1; i++)
{
DateTime dtRunningDate = new DateTime(2013, 5, i);
//select BR_SUP_CODE,
DataRow[] drAttendance = dtAttendance.Select("BR_SUP_CODE=" + SupId + " AND SMS_DATE=#" + dtRunningDate + "#", string.Empty);
if (drAttendance.Length == 1)
{
//CheckBox chkbx = new CheckBox();
//chkbx.Checked = true;
dr[i.ToString()] = true;
}
else
{
//CheckBox chkbx = new CheckBox();
//chkbx.Checked = false;
dr[i.ToString()] = false;
}
}
dtFinalData.Rows.Add(dr);
}
//<-- Looping each BR from tblBrList
#endregion
GridView1.DataSource = dtFinalData;
GridView1.DataBind();
Now i want to add checked image in place of true and unchecked image in place of false.how to bind grid view dynamically such that in place of disable check box i want to insert two types of image?
Your DataTable part is fine and continue to add the True/False text as per the logic. Now you should handle the GridView part. So, define an event handler for the OnRowDataBound event of GridView.
In this event only, check for the Text property of the cells, and if True/False, clear the cells and add the required image.
<asp:GridView ID="GridView1" OnRowDataBound="GridView1_RowDataBound" ... />
And your event handler will have code as below:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
Image chkImage = new Image();
chkImage.ImageUrl="~/images/Checked.png";
Image UnchkImage = new Image();
UnchkImage.ImageUrl = "~/images/UnChecked.png";
if (e.Row.RowType == DataControlRowType.DataRow)
{
// We will start from 3rd cell because the first 2 cells are
// for SupID & SupName, where we don't need to place images
for (int cellIndex = 2; cellIndex < GridView1.Columns.Count; cells++)
{
// Add Checked Image when cell text is true
if (e.Row.Cells[cellIndex].Text == "true")
{
// clear the cell and add only the image
e.Row.Cells[cellIndex].Controls.Clear();
e.Row.Cells[cellIndex].Controls.Add(chkImage);
}
// Add Unchecked Image when cell text is false
if (e.Row.Cells[cellIndex].Text == "false")
{
// clear the cell and add only the image
e.Row.Cells[cellIndex].Controls.Clear();
e.Row.Cells[cellIndex].Controls.Add(unchkImage);
}
}
}
}

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