Find which input radio button is checked in code behind - asp.net

I have the following ListView that contains Input radio buttons:
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource_BGlist">
<ItemTemplate>
<input id="Radio1" name="BG_name" type="radio" value="<%# Eval("BG_fileName") % >"/>
<asp:Label ID="BG_fileNameLabel" runat="server" Text='<%# Eval("BG_fileName") %>' />
</ItemTemplate>
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSource_BGlist" runat="server" ConnectionString="Data Source=tcp:cg26trmnla.database.windows.net,1433;Initial Catalog=cookniche;Integrated Security=False;User ID=PublicSQLcookniche#cg26trmnla;Password=Abounakhle80+;Connect Timeout=30;Encrypt=True" ProviderName="System.Data.SqlClient" SelectCommand="SELECT [BG_fileName] FROM [BackgroundImages]"></asp:SqlDataSource>
I want to check which radio button is checked from code behind. I'm using the following code but it's obviously not correct.
foreach (ListViewItem itemRow in this.ListView1.Items)
{
RadioButton radioBtn = new RadioButton();
radioBtn = (RadioButton)itemRow.FindControl("Radio1");
if (radioBtn.Checked)
{
//do stuff
}
}

You are doing almost right. Only few minor things needs to be changed in your code.
Add runat="Server" in your radio button. Because if it will not runat="server" then you will not find radiobutton at code behind. have a look at below HTML code:
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource_BGlist">
<ItemTemplate>
<input id="Radio1" runat="server" name="BG_name" type="radio" value="<%# Eval("BG_fileName") %>"/>
<asp:Label ID="BG_fileNameLabel" runat="server" Text='<%# Eval("BG_fileName") %>' />
</ItemTemplate>
</asp:ListView>
And in your code behind you are casting to RadioButton this RadioButton indicates server side control of radio button. Instead of that you should use HtmlInputRadioButton as shown below:
foreach (ListViewItem itemRow in this.ListView1.Items)
{
var radioBtn = (HtmlInputRadioButton)itemRow.FindControl("Radio1");
if (radioBtn.Checked)
{
// Do Stuff
}
}
To Apply Grouping with RadioButton
<asp:ListView ID="ListView1" runat="server">
<ItemTemplate>
<input runat="server" name="BG_name" type="radio" ID="radio1" value='<%# Eval("Id") %>' ClientIDMode="Static" class="radioBGName" />
<asp:Label ID="BG_fileNameLabel" runat="server" Text='<%# Eval("Title") %>' />
</ItemTemplate>
</asp:ListView>
<script type="text/javascript">
$('.radioBGName').click(function () {
var controlId = $(this).attr('name');
$('.radioBGName').each(function () {
if (controlId != $(this).attr('name')) {
$(this).removeAttr('checked');
}
});
});
</script>

protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
RadioButton c1 = (RadioButton)e.Item.FindControl("Radio1");
if (radioBtn.Checked)
{
//do stuff
}
}
}
UPDATE
in Page_Load you need to know the row index and retrieve the control like this
RadioButton radio= this.ListView1.Items[<row_index>].FindControl("Radio1") as RadioButton

Related

OnModeChanging Event of FormView fired and Code executed but result not shown

When FormView OnModeChangingEVent fired I want to Enable/disable Textbox depending on weather the checkbox checked or not.
But when i click Edit button OnModeChanging Event fired and code shown below exccuted but the result is not displayed after the Mode is changed(i.e Textbox 1 is not disabled when Checkbox1 is checked ). Can any one help me out?
<asp:formview ID="FormView1" OnModeChanging="FormView1_ModeChanging" runat="server">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CheckBox ID="CheckBox1" runat="server" />
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CheckBox ID="CheckBox1" runat="server" />
</InsertItemTemplate>
</asp:formview>
protected void FormView1_ModeChanging(object sender, FormViewModeEventArgs e)
{
switch (e.NewMode)
{
case FormViewMode.Edit:
TextBox TextBox1 = (TextBox)FormView1.FindControl("TextBox1");
CheckBox CheckBox1 = (CheckBox)FormView1.FindControl("CheckBox1");
if (CheckBox1.Checked)
{
TextBox1.Enabled = false;
}
else
{
TextBox1.Enabled = true;
}
break;
}
}

How to change dynamic css style of button of datalist on DataBinding

<asp:DataList ID="DataList1" runat="server" RepeatColumns="5" RepeatDirection="Horizontal"
onitemcommand="DataList1_ItemCommand"
onselectedindexchanged="DataList1_SelectedIndexChanged"
ondatabinding="DataList1_DataBinding">
<ItemTemplate>
<asp:HiddenField ID="Hdnqid" runat="server" Value='<%# Bind("Id") %>' />
<asp:HiddenField ID="HidnResultStatus" runat="server" Value='<%# Bind("ResultStatus") %>' />
<asp:Button ID="Butto" runat="server" Text='<%#Eval("Id") %>' CommandName="Save&Next"
CommandArgument='<%#Eval("Id") %>' />
</ItemTemplate>
</asp:DataList>
I want to change color of button accourding to value of table.
One way of doing this is using OnDataBound event of the data list. In the event you can get the button as well as your data item properties. Here you can change the properties of the button as below
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
Button button = e.Item.FindControl("Butto") as Button;
HiddenField HidnResultStatus = e.Item.FindControl("HidnResultStatus") as HiddenField;
string property = DataBinder.Eval(e.Item.DataItem, "colorproperty") as string;
//Here you can change the button color based on the value
if(HidnResultStatus.Value=="")
button.ForeColor = System.Drawing.Color.Black;
if(HidnResultStatus.Value=="1")
button.ForeColor = System.Drawing.Color.Brown;
}

How do i get the value of a datalist item with a button click

I have a dataList with a command button, i want to click the button and obtain the value of a field in the datalist view of the button i have clicked.
I have tried various solutions but keep getting
{"Object reference not set to an instance of an object."}
here is my datalist
<asp:DataList ID="DataList1" runat="server" DataKeyField="ID" DataSourceID="SqlDataSource1" Width="579px" OnItemCommand = "Datalist1_ItemCommand">
<ItemTemplate>
Epic:
<asp:Label ID="EpicLabel" runat="server" Text='<%# Eval("Epic") %>' />
<br />
ID:
<asp:Label ID="IDLabel" runat="server" Text='<%# Eval("ID") %>' />
<br />
Company:
<asp:Label ID="CompanyLabel" runat="server" Text='<%# Eval("Company") %>' />
<br />
Date:
<asp:Label ID="DateLabel" runat="server" Text='<%# Eval("Date") %>' />
<br />
time:
<asp:Label ID="timeLabel" runat="server" Text='<%# Eval("time") %>' />
<br />
NewsItem:
<asp:Label ID="NewsItemLabel" runat="server" Text='<%# Eval("NewsItem") %>' />
<br />
HeadLine:
<asp:Label ID="HeadLineLabel" runat="server" Text='<%# Eval("HeadLine") %>' />
<br />
<asp:Button ID="Button1" runat="server" CommandArgument='<%# Eval("Epic", "{0}") %>' Text="Button" />
<br />
</ItemTemplate>
</asp:DataList>
and her is my code behind
public void Datalist1_ItemCommand(object sender, DataListCommandEventArgs e)
{
var button = sender as Button;
/// if (button == null) return;
var dataListItem = button.NamingContainer as DataListItem;
if (dataListItem == null) return;
var currentKey = DataList1.DataKeys[dataListItem.ItemIndex];
var myLabel = button.Parent.Controls.Cast<Control>().FirstOrDefault(x => x.ID == "Epic") as Label;
/// if (myLabel == null) return;
var myLabelText = myLabel.Text;
}
You code do this using the following changes on your code;
on your button control:
<asp:Button ID="Button1" runat="server" CommandName="myCommand" Text="Button" />
on your ItemCommand event:
protected void DataList1_ItemCommand(object source,
DataListCommandEventArgs e)
{
switch (e.CommandName)
{
case "myCommand":
// more code could go here
Label myLabel = (Label)e.Item.FindControl("EpicLabel");
var myLabelText = myLabel.Text;
// more code could go here
break;
}
}
If I am not mistaken, the ID of the control you are looking for is actually called EpicLabel, not just Epic. If myLabel is what the debugger is saying is not set to an instance of an object, this is most likely your problem.
So this line:
var myLabel = button.Parent.Controls.Cast<Control>().FirstOrDefault(x => x.ID == "Epic") as Label;
would need to be:
var myLabel = button.Parent.Controls.Cast<Control>().FirstOrDefault(x => x.ID == "EpicLabel") as Label;

Can not get textbox value inside datalist

I am trying to get the value of textbox "Qty" inside a datalist. It does not work. What is wrong? I have both the CartItem label and the datelist inside the ajax updatepanel. Thanks for any help. Here is my code:
<asp:Label ID="CartItems" runat="server" Text="CartItem"></asp:Label>
<br />
<asp:DataList ID="DataList1" runat="server" CellPadding="10"
DataKeyField="product_id" DataSourceID="SqlDataSource1" RepeatColumns="2">
<ItemTemplate>
<asp:Label ID="product_id" runat="server"
Text='<%# Eval("product_id") %>' /><br/>
<asp:Label ID="product_name" runat="server"
Text='<%# Eval("product_name") %>' />
<br />
Qty
<br/>
<asp:TextBox ID="Qty" runat="server"></asp:TextBox>
<asp:Button ID="ButtonAddToCart" runat="server" Text="Add to Cart"
onClick="ButtonAddToCart_Click"/>
<br />
</ItemTemplate>
</asp:DataList>
and here is the button click event. The CartItem has null value:
protected void ButtonAddToCart_Click(object sender, EventArgs e)
{
CartItem.Text = DataList1.FindControl("Qty").ToString();
}
TextBox Qty = (TextBox)DataList1.FindControl("Qty");
if(Qty != null)
{
CartItem.Text =Qty.Text;
}
You can use NamingContainer or Parent to access sibling controls
protected void ButtonAddToCart_Click(object sender, EventArgs e)
{
var button = sender as Button;
var textbox = button.NamingContainer.FindControl("Qty") as TextBox;
CartItem.Text = textbox.Text;
}
I prefer you to use item_command event of the datalist
do some think like this.
<asp:Label ID="CartItems" runat="server" Text="CartItem"></asp:Label>
<br />
<asp:DataList ID="DataList1" runat="server" CellPadding="10" DataKeyField="product_id" DataSourceID="SqlDataSource1" RepeatColumns="2">
<ItemTemplate>
<asp:Label ID="product_id" runat="server"
Text='<%# Eval("product_id") %>' /><br/>
<asp:Label ID="product_name" runat="server"
Text='<%# Eval("product_name") %>' />
<br />
Qty
<br/>
<asp:TextBox ID="Qty" runat="server"></asp:TextBox>
<asp:Button ID="ButtonAddToCart" runat="server" Text="Add to Cart" CommandName="addtocart2" OnCommand="DataList1_ItemCommand"
/>
<br />
</ItemTemplate>
</asp:DataList>
Here is the item_command event that works.
public void DataList1_ItemCommand(object source, System.Web.UI.WebControls.CommandEventArgs e){
TextBox qtytxtbox = DataList1.FindControl("Qty") as TextBox;
}
You can do like this
protected void ButtonAddToCart_Click(object sender, EventArgs e)
{
Button ButtonAddToCart= (Button)sender;
DataListItem item = (DataListItem)ButtonAddToCart.NamingContainer;
var textbox = (TextBox)item.FindControl("Qty");
}
try this one
TextBox txtquantity = (TextBox)(e.Item.FindControl("Qty"));
simply use this......You will get the value in txtquantity

How to create a custom control dynamically?

Let me get this straight. I manage to create a custom Gridview with a single checkbox but my problem here is that I want to include multiple dynamic Checkbox.
Here is my code:
<%# Control Language="C#" AutoEventWireup="true" EnableTheming="true" CodeFile="GridviewControl.ascx.cs" Inherits="UserControl_GridviewControl" %>
<link href="../Template/CSS/Style.css"type="text/css" rel="Stylesheet" />
<div>
<span id="Span5" style="font-family: Arial; font-size:12px;" ><asp:Label ID="lblCount" runat="server" Text="0" Font-Bold="true"></asp:Label>
Record/s</span>
<span class="maintenance-btns">
<asp:Button ID="btnNew" runat="server" Text=" New " onclick="btnNew_Click"/>
<asp:Button ID="btnDel" runat="server" Text=" Delete " onclick="btnDel_Click"/>
</span>
</div>
<asp:Panel ID="pnlPc" runat="server" CssClass="div-grid" ScrollBars="Auto">
<asp:GridView ID="gvListing" runat="server" AllowPaging="True" AutoGenerateSelectButton="true"
OnRowDataBound="gvListing_RowDataBound" skinid="gvListing"
onselectedindexchanged="gvListing_SelectedIndexChanged"
onpageindexchanging="gvListing_PageIndexChanging" PageSize="50" >
<FooterStyle CssClass="grid-footer" />
<Columns>
<asp:TemplateField HeaderText="CheckAll">
<HeaderTemplate>
<asp:CheckBox ID="chkSelectAll" runat="server" AutoPostBack="true"
OnCheckedChanged="chkSelectAll_CheckedChanged" CssClass="select-all"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="true"
OnCheckedChanged="chkSelect_CheckedChanged" CssClass="listing-checkbox"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
In this gridview I only have a checkboxes at the first column. I want to put the dynamically generated checkboxes at the last column.
P.S.: How do I retrieve the id with those dynamically create checkboxes?
You can do like this
protected void gvData_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow objRow in gvData.Rows)
{
TableCell tcCheckCell = new TableCell();
var checkBox = new CheckBox();
checkBox.CheckedChanged += checkBox_CheckedChanged;
tcCheckCell.Controls.Add(checkBox);
objRow.Cells.AddAt(0, tcCheckCell);
}
}
void checkBox_CheckedChanged(object sender, EventArgs e)
{
//do something
}

Resources