I have a repeater with html table inside. In the html table I have a table cell with a check box.
I am trying to get the checked rows from the user after clicking a button but the result is always null.
asp.net markup:
<table id="tbl1" class="table">
<tr>
<th>test 1</th>
<th>test 2</th>
<th>test 3</th>
<th>test 4</th>
<th>Select</th>
</tr>
<asp:Repeater ID="rep" runat="server">
<ItemTemplate>
<tr id="tr1" runat="server">
<td>
<asp:Label ID="lbl1" runat="server" Text='<%#Eval("test1") %>'>' ></asp:Label>
</td>
<td>
<asp:Label ID="lbl2" runat="server" Text='<%#Eval("test2") %>'>' ></asp:Label>
</td>
<td>
<asp:Label ID="lbl3" runat="server" Text='<%#Eval("test3") %>'>' ></asp:Label>
</td>
<td>
<asp:Label ID="lbl4" runat="server" Text='<%#Eval("test4") %>'>' ></asp:Label>
</td>
<td id="td1" runat="server">
<asp:CheckBox ID="Select" runat="server" />
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
<asp:Button ID="btnSelect" runat="server" Text="Go" OnClick="btnSelect_Click" />
C# code:
protected void btnSelect_Click(object sender, EventArgs e)
{
foreach (RepeaterItem rpt in rep.Items)
{
CheckBox ckb = (CheckBox)rpt.FindControl("Select");
if (ckb.Checked) // Always Null
{
//
}
else
{
//
}
}
}
The problem is that you have another server control inside the repeater item. The Checkbox is not directly in the repeater item it is in the table row. You can extract the checkbox like this
CheckBox ckb = (CheckBox)rpt.FindControl("tr1").FindControl("Select");
if (ckb.Checked)
...
Of course this is bad since changing the layout will break your code. To remedy this you can write a recursive FindControl but it requires some more work.
Are you rebinding the DataSource for the Repeater on PostBack? This would cause the state of all the controls in the Repeater to be reset.
The problem might be that rpt.FindControl("Select") only searches only in the children of rpt. You can try this:
/// <summary>
/// Iterates throug all children and returns all of Type T.
/// </summary>
public static List<T> FindChildrenOfType<T>(Control control) where T : class
{
List<T> controls = new List<T>();
foreach (Control childControl in control.Controls)
{
if (childControl.Controls.Count > 0)
{
controls.AddRange(FindChildrenOfType<T>(childControl, comp));
}
if (childControl is T)
{
controls.Add(childControl as T);
}
}
return controls;
}
Use it like this:
var checkboxes = FindChildrenOfType<CheckBox>(rpt);
You can try this....
Aspx Code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Repeater ID="Repeater1" runat="server" >
<ItemTemplate>
<div>
<asp:CheckBox ID="CategoryID" runat="server" Text='<%# Eval("val") %>' />
</div>
</ItemTemplate>
</asp:Repeater>
<asp:Button Text="Click" OnClick="Button2_Click" runat="server" />
</form>
</body>
</html>
CS Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("val", typeof(string));
for (int i = 0; i < 10; i++)
dt.Rows.Add("testing" + i.ToString());
Repeater1.DataSource = dt;
Repeater1.DataBind();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
string Rpt = "Repeater Items Checked:<br />";
for (int i = 0; i < Repeater1.Items.Count; i++)
{
CheckBox chk = (CheckBox)Repeater1.Items[i].FindControl("CategoryID");
if (chk.Checked)
{
Rpt += (chk.Text + "<br />");
}
}
Response.Write(Rpt);
}
Refrenced By: http://www.codeproject.com/Questions/534719/GetplusSelectedplusCheckboxesplusinplusASPplusRepe
Related
Actually i am trying to redirect command argument of a button present in a data list to another page. I am using Request.QueryString method to access the command argument on another page with the help of command name of the button. Please help me with it...
this is code of button present inside Data List
<asp:Button ID="Button1" runat="server" Text="Read" CommandArgument='<%# Eval("id")%>' OnClick="Button1_Click" CommandName="content"/>
this is code present in DataList Item command function
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
Response.Redirect("content.aspx?content=" +e.CommandArgument.ToString());
}
this is the onclick function code
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("content.aspx");
}
this is the code on another page(content.aspx)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String id = Request.QueryString["content"];
Label1.Text = id;
}
}
this is entire datalist code
<asp:DataList ID="DataList1" runat="server" DataKeyField="Id" DataSourceID="SqlDataSource1" Height="657px" RepeatColumns="4" RepeatDirection="Horizontal" Width="1248px" OnItemCommand="DataList1_ItemCommand" OnItemDataBound="DataList1_ItemDataBound">
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<ItemStyle ForeColor="#000066" />
<ItemTemplate>
<table class="auto-style2">
<tr>
<td style="text-align: center">
<asp:Label ID="Label2" runat="server" Text='<%# Eval("name") %>'></asp:Label>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("Id") %>' Visible="False"></asp:Label>
</td>
</tr>
<tr>
<td style="text-align: center">
<asp:Image ID="Image2" runat="server" Height="250px" ImageUrl='<%# Eval("image") %>' Width="250px" />
</td>
</tr>
<tr>
<td style="text-align: center">
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
<br />
<asp:ImageButton ID="ImageButton1" runat="server" CommandName="addtofav" CommandArgument='<%# Eval("id")%>' Height="30px" Width="20px" />
</td>
</tr>
<tr>
<td style="text-align: center">
<asp:Button ID="Button1" runat="server" Text="Read" CommandArgument='<%# Eval("id")%>' OnClick="Button1_Click" CommandName="content"/>
</td>
</tr>
</table
<br />
<br />
</ItemTemplate>
<SelectedItemStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
it does redirect to another page(content.aspx) but the label does not show the querystring text.
Try updating the DataList1_ItemCommand event to this:
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "content")
{
Response.Redirect("content.aspx?content=" +e.CommandArgument.ToString());
}
}
also make sure you are checking IsPostBack in Page_Load method of this page code behind.
Yes i got the desired output. Actually i was also using another button to redirect to a diiferent page in DataList1_ItemCommand function. So i just needed to seperate the Response.redirects of the 2 buttons by putting them in if loop.
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "content")
{
Response.Redirect("content.aspx?content="+e.CommandArgument.ToString());
}
if (e.CommandName == "addtofav")
{
Response.Redirect("sortbyAZ.aspx?addtofav=" + e.CommandArgument.ToString());
}
}
Thanks You everybody for helping me out with this one
I think you are not casting the Request.QueryString["content"] to string format, try this
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String id = Request.QueryString["content"];
Label1.Text = id;
}
}
You can find all information you need in this tutorial. from #microsoft msdn
Best of luck
<%# Page Language="C#" AutoEventWireup="True" %>
<%# Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>DataList Select Example</title>
<script runat="server">
ICollection CreateDataSource()
{
// Create sample data for the DataList control.
DataTable dt = new DataTable();
DataRow dr;
// Define the columns of the table.
dt.Columns.Add(new DataColumn("Item", typeof(Int32)));
dt.Columns.Add(new DataColumn("Qty", typeof(Int32)));
dt.Columns.Add(new DataColumn("Price", typeof(double)));
// Populate the table with sample values.
for (int i = 0; i < 9; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = i * 2;
dr[2] = 1.23 * (i + 1);
dt.Rows.Add(dr);
}
DataView dv = new DataView(dt);
return dv;
}
void Page_Load(Object sender, EventArgs e)
{
// Load sample data only once, when the page is first loaded.
if (!IsPostBack)
{
ItemsList.DataSource = CreateDataSource();
ItemsList.DataBind();
}
}
void Item_Command(Object sender, DataListCommandEventArgs e)
{
// Set the SelectedIndex property to select an item in the DataList.
ItemsList.SelectedIndex = e.Item.ItemIndex;
// Rebind the data source to the DataList to refresh the control.
ItemsList.DataSource = CreateDataSource();
ItemsList.DataBind();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<h3>DataList Select Example</h3>
Click <b>Select</b> to select an item.
<br /><br />
<asp:DataList id="ItemsList"
GridLines="Both"
CellPadding="3"
CellSpacing="0"
OnItemCommand="Item_Command"
runat="server">
<HeaderStyle BackColor="#aaaadd">
</HeaderStyle>
<AlternatingItemStyle BackColor="Gainsboro">
</AlternatingItemStyle>
<SelectedItemStyle BackColor="Yellow">
</SelectedItemStyle>
<HeaderTemplate>
Items
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton id="SelectButton"
Text="Select"
CommandName="Select"
runat="server"/>
Item <%# DataBinder.Eval(Container.DataItem, "Item") %>
</ItemTemplate>
<SelectedItemTemplate>
Item:
<asp:Label id="ItemLabel"
Text='<%# DataBinder.Eval(Container.DataItem, "Item") %>'
runat="server"/>
<br />
Quantity:
<asp:Label id="QtyLabel"
Text='<%# DataBinder.Eval(Container.DataItem, "Qty") %>'
runat="server"/>
<br />
Price:
<asp:Label id="PriceLabel"
Text='<%# DataBinder.Eval(Container.DataItem, "Price", "{0:c}")
%>'
runat="server"/>
</SelectedItemTemplate>
</asp:DataList>
</form>
</body>
</html>
By the way I think you don't need define Button Click event. Already defined path with variable. Just convert button to Link Button and remove Button Click Event
Here is my messageview.aspx, which has list view to show user messages.
On delete button click, I want to capture the current table row value, and call the sql stored procedure accordingly. However, I am unable to access the fields like Sender Email-ID, Sender Role, and Message inside delete button click function. how can I do so?
<%# Page Title="" Language="C#" MasterPageFile="~/DefaultLayout.Master" AutoEventWireup="true" CodeBehind="MessageView.aspx.cs" Inherits="SchoolMgmtSystem.MessageView" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="jumbotron">
<h1>Inbox</h1>
</div>
<asp:ListView ID="lvgetMessages" runat="server" OnSelectedIndexChanged="lvgetMessages_SelectedIndexChanged">
<EmptyDataTemplate>
<table runat="server" style="background-color: #FFFFFF; border-collapse: collapse; border-color: #999999; border-style: none; border-width: 1px;">
<tr>
<td>No data was returned.</td>
</tr>
</table>
</EmptyDataTemplate>
<LayoutTemplate>
<table class="table table-border">
<tr>
<th> Sender Email ID</th>
<th> Sender Role </th>
<th> Message</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr style="background-color: #DCDCDC; color: #000000;">
<td>
<asp:Label ID="emailIDLabel" runat="server" Text='<%# Eval("[SenderEmailID]") %>' />
</td>
<td>
<asp:Label ID="SenderRoleLabel" runat="server" Text='<%# Eval("RoleName") %>' />
</td>
<td>
<asp:Label ID="MessageLabel" runat="server" Text='<%# Eval("[Message]") %>' />
</td>
<td>
<asp:Button ID="ButtonDelete" runat="server" Text="Delete" onclick="ButtonDelete_Click" UseSubmitBehavior="False" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<div class="form-group" runat="server" style="display:block">
<asp:Button ID="ButtonBack" runat="server" Text="Back" CssClass="btn-primary center-block" OnClick="ButtonBack_Click" />
</div>
</asp:Content>
The code behind message view is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BAL;
using System.Data;
namespace SchoolMgmtSystem
{
public partial class MessageView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lvgetMessages.DataSource = null;
lvgetMessages.DataBind();
String roleId = Request.QueryString["RoleId"];
String userId = Request.QueryString["UserId"];
String userEmailId = AdminBizz.GetEmailId(userId, roleId);
DataTable dtMessageInfo = RoleBizz.GetUserMessages(userEmailId);
if (dtMessageInfo.Rows.Count > 0)
{
lvgetMessages.DataSource = dtMessageInfo;
lvgetMessages.DataBind();
}
}
protected void lvgetMessages_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void ButtonDelete_Click(object sender, EventArgs e)
{
}
protected void ButtonBack_Click(object sender, EventArgs e)
{
String roleId = Request.QueryString["RoleId"];
String userId = Request.QueryString["UserId"];
Response.Redirect("MessageSend.aspx?UserId=" + userId + "&RoleId=" + roleId);
}
}
}
Here is the screen shot -
What you can probably do is get the NamingContainer of your delete button and find the other controls within it.
protected void ButtonDelete_Click(object sender, EventArgs e)
{
var control = (Control)sender;
var container = control.NamingContainer;
// access your controls this way
var emailIDLabel= container.FindControl("emailIDLabel") as Label;
var senderRoleLabel = container.FindControl("SenderRoleLabel") as Label;
var messageLabel = container.FindControl("MessageLabel") as Label;
}
You can do something like the answer for this question.
But remember to validate the value (with int.TryParse(string) for example).
<asp:Button ID="ButtonDelete" runat="server" Text="Delete"
OnClick="ButtonDelete_Click"
UseSubmitBehavior="False"
CommandName="Deleterecord"
CommandArgument='<%# Eval("[SenderEmailID]") %>'/>
protected void ButtonDelete_Click(object sender, EventArgs e)
{
int id;
var button = (Button)sender;
if(!int.TryParse(button.CommandArgument, out id))
{
// log.Write("possible sql injection");
return;
}
// do what you want
}
My list is populated from a webservice call.
If i populate the list manually line by line its ok. I can select the item and return the selectem item with no problem e.g.
List<ListItem> oList = new List<ListItem>();
oList.Add(new ListItem("User", "0"));
oList.Add(new ListItem("Manager", "1"));
cboUsers.DataSource = oList
Thats not practical as the list I want to bind to is Dynamic, e.g.
cboUsers.DataSource = MyWebService.GetUsers() // returns List<ListItem>
No matter what I do in code I cannot get the the selected item from the list and the list ALWAYS resets itself.
Both items of code are enclosed within
if (!IsPostBack)
But when the list is bound to a web service no matter what I do (ViewState, Session anything) the list is ALWAYS reset after postback and I can NEVER get the selected item correctly.
I have tried every combination of properties on pages, controls in code and in the mark up and nothing works. I have looked at loads of articles on here and other websites and none of their examples work.
Any help would be appreciated.
[EDIT]
The full code is below.
(cboAccess, manually filled work just fine as expected)
(cboDept will fill and display but after that I can get no selection from it)
You make a selection from the dropdown (cboDept) then click the Add button (cmdAdd) which adds the text selection from the list to my database using my web service. The selection is ALWAYS shown to be the first item no matter what I select.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
AttendanceWebServices.Service1Client oServices = new AttendanceWebServices.Service1Client();
List<ListItem> oList = new List<ListItem>();
oList.Add(new ListItem("Normal User", "0"));
oList.Add(new ListItem("Manager", "10"));
cboAccess.DataTextField = "Text";
cboAccess.DataValueField = "Value";
cboAccess.DataSource = oList;
cboAccess.DataBind();
cboDept.DataSource = oServices.GetTeamGroups().ToList();
cboDept.DataValueField = "Value";
cboDept.DataTextField = "Text";
cboDept.DataBind();
}
}
protected void cmdAdd_Click(object sender, EventArgs e)
{
AttendanceWebServices.Service1Client oServices = new AttendanceWebServices.Service1Client();
string sDept = ((ListItem)cboDept.SelectedItem).Text;
oServices.AddNewUser(sDept);
}
}
[EDIT2 - HTML]
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="adduser.ascx.cs" Inherits="AttendanceWeb2.adduser" %>
<style type="text/css">
.style1
{
width: 100%;
}
</style>
<p>
</p>
<asp:scriptmanager runat="server" id="scm1">
</asp:scriptmanager>
<table class="style1">
<tr>
<td>
Name</td>
<td>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Department</td>
<td>
<asp:updatepanel runat="server">
<ContentTemplate>
<asp:DropDownList ID="cboDept" runat="server">
</asp:DropDownList>
</ContentTemplate>
<triggers>
<asp:AsyncPostBackTrigger ControlID="cmdAdd" />
</triggers>
</asp:updatepanel>
</td>
</tr>
<tr>
<td>
Employee ID</td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Access Level</td>
<td>
<asp:dropdownlist runat="server" id="cboAccess"></asp:dropdownlist>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="cmdAdd" runat="server" onclick="cmdAdd_Click" Text="Add"
Width="100px" />
<asp:Button ID="cmdDelete" runat="server" onclick="cmdDelete_Click" Text="Delete"
Width="100px" />
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
</tr>
</table>
[EDIT 3] - Simplified Version (Still does not work)
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="AttendanceWeb2._default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="cboDept" runat="server"></asp:DropDownList>
<asp:Button ID="cmdAdd" runat="server" Text="Add" Width="100px"
onclick="cmdAdd_Click" />
</div>
</form>
</body>
</html>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
AttendanceWebServices.Service1Client oServices = new AttendanceWebServices.Service1Client();
cboDept.DataSource = oServices.GetTeamGroups().ToList();
cboDept.DataValueField = "Value";
cboDept.DataTextField = "Text";
cboDept.DataBind();
}
}
protected void cmdAdd_Click(object sender, EventArgs e)
{
ListItem oItem = cboDept.SelectedItem;
string sText = oItem.Text;
string sValue = oItem.Value;
}
Make sure that you have EnableViewState set to True for your cboDept control.
EDIT
Put your table inside a form. Example:
<form id="form1" runat="server">
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<asp:Button type="submit" ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
I am trying to input logic in the source view in Asp.Net ListView. The problem is that the program is writing on the screen false or true when executing "If (isItTrue(test))". Does anyone know how to solve this problem?
<%# test= Eval("testId")%>
<%
If (isItTrue(test)) Then
%>
<asp:Button ID="btnTest" runat="server" Text="Like" />
<%
Else
%>
<asp:Label runat="server" Text="hello" </asp:Label>
<%
End If
%>
You could use ItemDataBound to check informations like this and show or hide the controls using your condition. try something like this in your code behine:
protected void ListViewTest_ItemDataBound(object sender, ListViewItemEventArgs e)
{
// if it is data item
if (e.Item.ItemType == ListViewItemType.DataItem)
{
// call your function
if (isItTrue("test"))
{
// show the button
e.Item.FindControl("btnTest").Visible = true;
}
else
{
// show the label
e.Item.FindControl("lblTest").Visible = true;
}
}
}
And in your Listview, you could do something like this, setting the event and adding the controls on the place holder
<asp:ListView ID="ListViewTest" DataSourceID="..." OnItemDataBound="ListViewTest_ItemDataBound" runat="server">
<LayoutTemplate>
<table>
<tr>
<th>Column Name</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr style="background-color: #CAEEFF" runat="server">
<td>
<%-- both controls are here --%>
<asp:Button ID="btnTest" runat="server" Visible="false" Text="Like"></asp:Button>
<asp:Label ID="lblTest" runat="server" Visible="false" Text="hello"></asp:Label>
</td>
</tr>
</ItemTemplate>
</asp:ListView>
Are you sure it's not this line: <%# test= Eval("testId")%> that is writing true or false to the output?
i want set class for repeater when doPostBack for those dataID i wan but dun noe can/cannot?
below code is just for example showing:
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePartialRendering="true" runat="server" EnablePageMethods="true" />
<asp:UpdatePanel ID="UpdatePanel2" runat="server" >
<ContentTemplate>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="dsInbox">
<ItemTemplate>
<tr id="trInbox">
<td width="370px" height="25px"><div align="left" class="style95"> <%# DisplaySubject(Eval("inbSubject").ToString(), Eval("inbMsg").ToString())%></div></td>
<td width="80px" height="25px"><div align="left" class="style95"> <%# Eval("inbCreatedAt","{0:MM-dd-yyyy}") %></div></td>
<td width="94px" height="25px"><div align="left" class="style95"> <%# Eval("DataId") %></div></td>
</tr>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
in behind Code C# i can create the class/style i wan
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
Repeater1.DataBind();
//find the data row ID and set class/style when loaded
}
}
If you are wanting to set a class per each row bound, and need the data ID, then your best approach is to handle it as each row is bound:
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="dsInbox"
OnItemDataBound="Repeater1_ItemDataBound">
and in code-behind:
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
{
MyType myItem = (MyType)e.Item.DataItem;
var dataId = myItem.DataId;
// Do whatever you need here.
}
}