looping through checkboxes and inserting checkbox values to DB - c#

ASPX Page:
<asp:ListView ID="lvSubjects" runat="server" >
<LayoutTemplate>
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
</LayoutTemplate>
<ItemTemplate>
<asp:CheckBox ID="cbRegularSubjects" Text=<%# Eval("SubjectName") %> runat="server" />
</ItemTemplate>
<AlternatingItemTemplate>
<asp:CheckBox ID="cbRegularSubjects" Text=<%# Eval("SubjectName") %> runat="server" />
</AlternatingItemTemplate>
</asp:ListView>
Code Behind:
For Each ctrl As Control In Page.Controls
If TypeOf ctrl Is CheckBox AndAlso CType(ctrl, CheckBox).Checked Then
'**Here I want to get the text of the check box and insert into the DB**
End If
Next
Where am i going wrong??i do not get any error...but this code is not working for me.

For i As Integer = 0 To lvSubjects.Items.Count - 1
Dim coll As ControlCollection = lvSubjects.Items(i).Controls
For Each c As Control In coll
If TypeOf c Is CheckBox Then
Dim box As CheckBox = CType(c, CheckBox)
If box.Checked Then
MsgBox(box.Text)
End If
End If
Next c
Next i

you are only searching in Page.Controls whereas your checkboxes are inside deeper in page control hierarichy.
foreach (ListViewItem row in listView.Rows)
{
if (row.ItemType == ListViewItemType.DataItem)
{
CheckBox chk = row.FindControl("Checkboxid");
if (chk.Checked)
{
//Write code to store this checkbox value to database here
}
}
}
Please change the code in VB with proper control name

Related

Add hidden field to checkboxlist

I have a CheckBoxList, in addition to checkbox and label I have to add a hidden field for each list item in the CheckBoxList. Is there a way to achieve this?
Thanks in advance.
You can achieve this by using a Repeater instead of a CheckBoxList control. On the plus side, this gives you more control over the generated HTML which might come handy anyway if you plan to access the items with jQuery; on the other hand you have to implement methods like retrieving the checked items for yourself.
The following sample shows the basic markup:
<asp:Repeater ID="rpt" runat="server">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:CheckBox ID="chk" runat="server" Text='<%# Eval("Item1") %>' />
<asp:HiddenField ID="hidden" runat="server" Value='<%# Eval("Item2") %>' />
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
In this sample, I have bound the repeater to a list of Tuple<string, string> values. You can retrieve the selected items like this by iterating the items of the repeater and retrieving the CheckBox and HiddenField:
private IEnumerable<Tuple<string, string>> GetSelectedItems()
{
var lst = new List<Tuple<string, string>>();
var items = rpt.Items
.OfType<RepeaterItem>()
.Where(x => x.ItemType == ListItemType.Item
|| x.ItemType == ListItemType.AlternatingItem);
foreach (var item in items)
{
var chk = (CheckBox)item.FindControl("chk");
if (chk.Checked)
{
var hidden = (HiddenField)item.FindControl("hidden");
lst.Add(Tuple.Create(chk.Text, hidden.Value));
}
}
return lst.ToArray();
}

identify selected checkboxes in asp listview object

I have been trying to understand the ListView object in ASP but I'm unable to programmatically get the selected checkboxes or iterate through them. Below are the two methods I'm seeing posted the most here on SO, but so far everything I've tried hasn't seemed to work for me.
Any help would greatly be appreciated.
.ASPX Page
<asp:ListView ID="courseListView" runat="server">
<LayoutTemplate>
<table><asp:PlaceHolder runat="server" ID="itemPlaceholder">
</asp:PlaceHolder></table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td><asp:CheckBox ID="courseIdchk" Text='<%# Eval("CourseId") %>' runat="server" /></td>
<td><asp:Label ID="courseTitleLbl" Text='<%# Eval("title") %>' runat="server" /></td>
</tr>
</ItemTemplate>
</asp:ListView>
.CS Code Behind
//Method #1
string result = string.Join(", ", courseListView.Controls.OfType<CheckBox>()
.Select(chk => chk.Text));
string result = "";
//Method #2
foreach (CheckBox ctrl in courseListView.Controls.OfType<CheckBox>())
{
result2 += ctrl.Text;
}
Response.Write("<p>The result is " + result);
Response.Write("<p>The result is " + result2);
Response.End();
I'm not near the Visual Studio but off the top of my head I see 2 reasons why it does not iterate.
1. You should bind this ListView to a source in OnLoad method:
if (!IsPostback) {
courseListView.DataSource = GetCourses();
courseListView.DataBind();
}
2. courseListView.Controls does not contain items of type CheckBox, so OfType<CheckBox>() filters out all elements. If you debug and put a breakpoint over foreach (CheckBox ctrl in courseListView.Controls.OfType<CheckBox>()), you will see that CheckBox is one of the subchildren of courseListView., so build your logic depending on which control contain CheckBoxes write the appropriate logic to get it like:
var checkBox = courseListView.Controls.Cast<Control>().First().FindControl("courseIdchk");
Again, the code above assumes that checkbox is a child of a control, which is an only child of your courseListView.
UPDATE
var findCheckedQuery = courseListView.Controls[0]
.Controls
.Cast<Control>()
.Select(ctrl => ctrl.FindControl("chkBox") as CheckBox)
.Where(chk => chk != null && chk.Checked);
result = string.Join(":", findCheckedQuery.Select(x => x.Text).ToArray());
UPDATE2
ASPX:
<asp:Repeater ID="courseListView" runat="server">
<ItemTemplate>
<asp:CheckBox ID="chkBox" data-id="<%#((Course)Container.DataItem).CourseId %>" Text="<%#((Course)Container.DataItem).Title %>" runat="server" />
<br/>
</ItemTemplate>
</asp:Repeater>
<asp:Button runat="server" UseSubmitBehavior="True" Text="Submit"/>
Code-behind:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!IsPostBack)
{
courseListView.DataSource = GetCourses();
courseListView.DataBind();
}
else
{
var result = string.Empty;
var findCheckedQuery = courseListView
.Controls
.Cast<Control>()
.Select(x => (CheckBox)x.FindControl("chkBox"))
.Where(x => x.Checked)
.Select(x => x.Text);
result = string.Join(", ", findCheckedQuery.ToArray());
}
}

Stored Value in Checkbox and Capture Submitted Values Checked

I have an ASP:DataList. Inside the DataList, I have the code below which displays the Name and Checkbox for each row.
What I would like to do is:
Store the Name in a hidden field.
Loop through all the checkboxes, find the ones that are checked and INSERT the value into the database.
If possible, please provide some sample code.
<td style="width: 600px"><%#Eval("Name></td>
<td style="width: 20px">
<asp:CheckBox ID="chkName" Text='<%# Eval("Name") %>' runat="server" />
</td>
what you are doing is fine.
Just in your postback, loop though the check box and check
foreach (Checkbox cb in YOurcheckboxlist)
{
if (cb.Checked) {
// get the name and insert
}
}
Had this situation before, this is what I did,
in the form_Sumbit event,
foreach (Control ctl in form1.Controls)
{
if (ctl is CheckBox)
{
//check for checked or not and store the value into an array or a List.
}
}
Not a perfect solution, let's see if someone can come up with a better idea.

Error while data binding to grid [duplicate]

This question already has answers here:
Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control
(4 answers)
Closed 9 years ago.
I have following code in gridview:
<% If Eval("LabelType").ToString() = "Singleline" Then%> <asp:TextBox ID="txtSingleLine" runat="server" ></asp:TextBox> <% End If%>
<% If Eval("LabelType").ToString() = "Multiline" Then%> <asp:TextBox ID="txtMultiline" runat="server" TextMode="MultiLine" ></asp:TextBox> <% End If%>
<% If Eval("LabelType").ToString() = "Image" Then%> <asp:FileUpload ID="FileUpload1" runat="server" /> <% End If%>
I am getting following error:
Databinding methods such as Eval(), XPath(), and Bind() can only be
used in the context of a databound control
From this question i came to know that # should be added, but when i added as:
It was not accepting this (showing blue line below whole statement).
Please tell me where i am making mistake.
Please help me.
I am using vb.net but answer in c# is also helpful.
You could try setting the visibility on each control based on the value of LabelType like so:
<asp:TextBox ID="txtSingleLine" runat="server" Visible="<%# Eval("LabelType").ToString() == "Singleline" %>"></asp:TextBox>
<asp:TextBox ID="txtMultiline" runat="server" TextMode="MultiLine" Visible="<%# Eval("LabelType").ToString() == "Multiline" %>" ></asp:TextBox>
<asp:FileUpload ID="FileUpload1" runat="server" Visible="<%# Eval("LabelType").ToString() == "Image" %>" />
Like the error says you cannot have an Eval outside of data bound control, so I would recommend that you dynamically insert the controls into a PlaceHolder control, like this:
Markup:
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
Code-behind:
If LabelType = "Singleline" Then
' Create textbox and add to placeholder
Dim textbox = New TextBox()
textbox.ID = "txtSingleLine"
PlaceHolder1.Controls.Add(textbox)
Else If LabelType = "Multiline" Then
' Create textbox with multi-line text mode and add to placeholder
Dim multilinetextbox = New TextBox()
multilinetextbox.ID = "txtMultiline"
PlaceHolder1.Controls.Add(multilinetextbox)
Else If LabelType = "Image" Then
' Create file upload and add to placeholder
Dim fileupload = New FileUpload()
fileupload.ID = "FileUpload1"
PlaceHolder1.Controls.Add(fileupload)
End If
Note: LabelType in the code above is the string representation of what you were doing in Eval("LabelType").ToString().

Accesing a CheckBox that's inside a Repeater

In my repeater's ItemTemplate I've a CheckBox and a disabled TextBox, I need to implement this idea: TextBox only gets enabled if the the CheckBox is checked .. so I set the CheckBox AutoPostBack to true and I tried to put this code in ItemDataBound. but I can't find my control which is weird because I use the same code but in loop "MyRptr.Item[i].FindControl...." and it works! .. I don't want to loop through all the Items, I just wish If I can know the Item number or location in which the CheckBox was created. and I've also tried to create an event handles for the CheckBox's CheckedChanged event but I can't find the CheckBox either!
protected void MyRptr_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
CheckBox ChkBx = e.Item.FindControl("IsSelected_ChkBx") as CheckBox;
if (ChkBx.Checked == true)
{
TextBox TxtBx = e.Item.FindControl("Value_TxtBx") as TextBox;
TxtBx.Enabled = true;
}
}
<asp:Repeater ID="MyRptr" runat="server"
onitemdatabound="MyRptr_ItemDataBound">
<ItemTemplate>
<asp:CheckBox ID="IsSelected_ChkBx" runat="server" Text='<%# Eval("Item") %>' AutoPostBack="True" OnCheckedChanged="IsSelected_ChkBx_CheckedChanged" />
<asp:TextBox ID="Value_TxtBx" runat="server" Enabled="false"></asp:TextBox>
<asp:HiddenField ID="ID_HdnFld" runat="server" Value='<%# Eval("ID") %>' />
</ItemTemplate>
<SeparatorTemplate>
<br></br>
</SeparatorTemplate>
</asp:Repeater>
So basically I need a clean and simple way to implement my logic and If I could get an explanation for what's happening it would be great, so any ideas =) ?
You can find your textbox as follow, but I think its better use the jQuery instead of server-side event
protected void IsSelected_ChkBx_CheckedChanged(object sender, EventArgs e)
{
var ch = (CheckBox)sender;
var txt = ch.Parent.FindControl("Value_TxtBx") as TextBox;
}

Categories

Resources