Problem with usage of RadioButton in GridView in ASP.NET - c#

<asp:TemplateField HeaderText="Select One">
<ItemTemplate>
<input name="MyRadioButton" type="radio" />
</ItemTemplate>
</asp:TemplateField>
aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow di in GridView1.Rows)
{
RadioButton rad = (RadioButton)di.FindControl("MyRadioButton");
//Giving Error:Object reference not set to an instance of an object.
if (rad.Checked&&rad!=null)
{
s = di.Cells[1].Text;
}
}
Response.Redirect("applicants.aspx?form=" +s);
}
I couldn't get the row which is selected in RadioButton. Can you help me with this please.

You can only use FindControl with server-side controls. Replace your <input> HTML element with an ASP.NET radio button, e.g:
<asp:RadioButton ID="MyRadioButton" runat="server" ... />

you have to use runat="server"
<input name="MyRadioButton" type="radio" runat="server" id="MyRadioButton" />

As already mentioned, add runat="server" and change order of conditions evaluated from if (rad.Checked&&rad!=null) to if (rad!=null && rad.Checked)
By the way it's not so easy to make radiobuttons in GridView column exclusive. Look at this link if you will stumble on problem: Adding a GridView Column of Radio Buttons

Related

How to get duplicate ID ASP elements from codebehind C#

My code:
<asp:DataList ID="datalist" runat="server" >
<ItemTemplate>
<asp:Textbox ID="Values" runat="server" type="text" />
</ItemTemplate>
</asp:DataList>
<asp:Button ID="Button1" runat="server" Text="SEND" OnClick="send" />
How could I get each Values ID elements of the DataList from code behind in C# ?
You loop all the items in the DataList and use FindControl to locate the TextBox.
protected void send(object sender, EventArgs e)
{
//loop all the items in the datalist
foreach (DataListItem item in datalist.Items)
{
//find the textbox with findcontrol
TextBox tb = item.FindControl("Values") as TextBox;
//do something with the textbox content
string value = tb.Text;
}
}

Get data from modalpopupextender's panel

I have a GridView and a column in GridView which has a linkButton that opens a modalpopupextender on click. I am able to bind data in popextender panel but now i want to retrieve data from that panel.
I am getting data from each GridRow like:
foreach (GridViewRow row in MyGridView.Rows)
{
Label Date = (Label)row.Cells[0].FindControl("DateId");
string date = Date.Text;
//Code to get linkButton(asp:ModalpopUpextender) and data from
//asp:panel of ModalpopUpextender
}
I have searched around for answers but wasn't able to find a solution to my problem.
Thanks in advance.
Assuming you are having a setup like this
<ajaxToolKit:ModalPopupExtender
ID="mdlPopup" runat="server" TargetControlID="btnShowPopup" PopupControlID="pnlPopup"
CancelControlID="btnClose" BackgroundCssClass="modalBackground" />
<asp:Panel ID="pnlPopup" runat="server" Width="500px" style="display:none">
<asp:UpdatePanel ID="updPnlCustomerDetail" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblCustomerDetail" runat="server" Text="Customer Detail" Width="95%" />
</ContentTemplate>
</asp:UpdatePanel>
You might try finding your panel first and then drill down to the required control.I would suggest putting this code in the row editing event
gridViewTest_RowEditing(object sender, GridViewEditEventArgs e)
{
gridViewTest.EditIndex=e.NewEditIndex;
Panel myPanel = (Panel)gridViewTest.Rows(gridViewTest.EditIndex).FindControl("pnlPopup");
Label myLabel = (Label)myPanel.Findcontrol("lblCustomerDetail");
}
//then do stuff with the label.
Thanks Abide for the useful post...finally i found the solution...
Panel.FindControl("ControlId");
does not work fine because somtimes panel is not added to the page.
we can use this code.It works fine.
foreach( Control cntrl in Panel.Controls )
{
if(cntrl.ID == "RequiredConteolId")
{
//your application code goes here...
}
}

How to reference XML data that isn't bound to a repeater

C# newbie asking, so if the question is stupid or the answer is really obvious, it's probably because I don't fully understand how XmlDataSource works.
Given the following XML file "super-simple-xml.xml" (formatted to save some space),
<items>
<item> <one id="ms">Microsoft</one> <two>MSFT</two> </item>
<item> <one id="in">Intel</one> <two>INTC</two> </item>
<item> <one id="de">Dell</one> <two>DELL</two> </item>
</items>
a repeater that looks something like this,
<asp:Repeater id="SuperSimple" runat="server" OnItemCommand="SuperSimple_ItemDataBound">
<HeaderTemplate>
<table border="1"><tr><th>Company</th><th>Symbol</th><th>Wrong</th></tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><asp:Label Text=<%#XPath("one") %> runat="server" /></td>
<td><asp:CheckBox Text=<%#XPath("two") %> runat="server" id="symbol" /></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
<asp:Button id="buttonOne" Text="Submit!" runat="server" />
</FooterTemplate>
</asp:Repeater>
and the following to bind the XML:
private void Page_Load(object sender, EventArgs e)
{
XmlDataSource xmlSource = new XmlDataSource();
xmlSource.DataFile = "super-simple-xml.xml";
xmlSource.XPath = "items/item";
if (!IsPostBack) // Did this to prevent an error
{
SuperSimple.DataSource = xmlSource;
SuperSimple.DataBind();
}
}
How would I go about pulling the id from each XML entry into a class or variable?
The idea here is that I am displaying the items in a Repeater. I added checkboxes, so I can check any of the <two> entries, and then press Submit. When it posts back, I want to store the checked entry in a class I've made. Getting <one> and <two> in are easy enough because they have IDs in the Repeater that I can reference. But the id attribute in the XML is never called, so I don't know how to get to it. I want to have the id in the class to reference as I pass the data along. Is this possible, and how do I do it?
Use the XPath # syntax for getting an attribute:
<%# XPath("one/#id") %>
You can bind this expression to a HiddenField and access that in the postback:
<asp:HiddenField runat="server" ID="hidID" Value='<%# XPath("one/#id") %>' />
Add a command button to the <ItemTemplate>:
<asp:Button runat="server" ID="btnGetID" Text="Get ID" CommandName="GetID" />
In the OnItemCommand event:
protected void SuperSimple_ItemDataBound(object sender, RepeaterCommandEventArgs e)
{
//check the item type, headers won't contain the control
if (e.CommandName == "GetID")
{
//find the control and put it's value into a variable
HiddenField hidID = (HiddenField)e.Item.FindControl("hidID");
string strID = hidID.Value;
}
}
This is an alternative (I originally posted because I was confused by the name of your OnItemCommand event and thought you wanted the values at DataBinding time):
In your <ItemTemplate>:
<asp:Button runat="server" ID="btnGetID" OnClick="btnGetID_Click" Text="Get ID" />
Code-behind:
protected void btnGetID_Click(object sender, e as EventArgs)
{
//sender is the button
Button btnGetID = (Button)sender;
//the button's parent control is the RepeaterItem
RepeaterItem theItem = (RepeaterItem)sender.Parent;
//find the hidden field in the RepeaterItem
HiddenField hidID = (HiddenField)theItem.FindControl("hidID");
//assign to variable
string strID = hidID.Value;
}
Maybe this helps, problem could be in wrong xml structure.
http://forums.asp.net/t/1813664.aspx/1?getting+xml+node+id+number

Switch Div Class in Repeater based on Checkbox.Checked Using C#

I have a repeater that will present a set of titles and checkboxes (some checked some not). Each is wrapped in a div with a background colour. All I want to do is change the background colour for the checkboxes that are already checked so they are easily identified on the page.
Here's the repeater:
<asp:Repeater ID="rptCartridges" runat="server" OnItemDataBound="rp_ItemDataBound">
<ItemTemplate>
<div class="cartridgebox">
<span class="cartridgeboxl"><%#Eval("cartName") %></span>
<span class="cartridgeboxr">
<asp:CheckBox ID="chkCart" name="chkbox" Checked = '<%#Convert.ToBoolean(DataBinder.Eval(Container.DataItem, "cartChecked"))%>' runat="server" />
<asp:HiddenField ID="hfCartID" runat="server" Value='<%#DataBinder.Eval(Container.DataItem, "cartID")%>' />
</span>
</div>
</ItemTemplate>
</asp:Repeater>
All I really want to do is change the class cartridgebox to cartridgeboxchecked if the checkbox is returned as checked.
I have tried manipulating rp_ItemDataBound. Where it goes wrong is the actual changing of the class inline. I've tried using if statements, add runat="server" to the div and populating a variable and then using Response.Write inside the class statement. But nothing seems to work.
What seems the neatest way would be to use rp_ItemDataBound like so:
protected void rp_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
string chkboxClass = "cartridgebox";
CheckBox chk = (CheckBox)e.Item.FindControl("chkCart");
HiddenField hfCartID = (HiddenField)e.Item.FindControl("hfCartID");
// Adding the hide.Value Attribute to the chk.Text field.
chk.Attributes.Add("Text", hfCartID.Value);
if (chk.Checked == true)
{
chkboxClass = "cartridgeboxchecked";
}
else
{
chkboxClass = "cartridgebox";
}
}
But I lack the understanding to pass the variable chkboxClass to the div's class dynamically. Of course I am probably looking at this completely wrong so any guidance would be appreciated.
Use following markup for div in ItemTemplate : <div class='<%# ((bool)Eval("cartChecked"))? "cartridgeboxchecked" : "cartridgeboxl" %>' >
If you need to change div's class on checkbox change immediatelly, consider to add onclick client-side event handler to checkbox in ItemDataBound Repeater's event handler

How to pass in runtime a index of row for ListView?

I have an question, On my page i have a ListView control, I also have a button that has CommandArgument. I know i can read and find a control in the ListView as :
ListView.Items[i].FindControl("controlname");
and my button in ListView is like that
asp:Button ID="WisdomButton" runat="server" CommandName="UpdateWisdom" CommandArgument='<%# need my index for Item[i] to post here %>'
OnCommand="UpdateWisdom" Text="Update" />
I want to add index value in runtime to the CommantParameter, so when i go to the Function onCommand i will know exactly from what row[i] i Need to get my controls from ListView.
So my question is, how do i dinamicly add index of ListView.Rows[i] into CommmandArgument for the Button in runtime ?
Thanks in advance.
Check out the API
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listviewcommandeventargs.aspx
The ListViewCommandEventArgs item has an index, IE it is already available in the argument
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
int i = dataItem.DisplayIndex;
But from here you will have access to those controls
e.Item.FindConrol("controlName");
If you are calling the method a different way you could aways assign the index through an ItemDataBound Event
void MyListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
((Button)e.Item.FindControl("WisdomButton")).CommandArgument = ((ListViewDataItem)e.Item).DisplayIndex;
}
OR try something like this for giggles
<asp:Button runat="server" CommandArgument='<%# DisplayIndex %>'/>
// OR
<asp:Button runat="server" CommandArgument='<%# NextIndex() %>'/>
It might help to know a little bit more about what your are trying to do. If your end goal is to get any of the properties from your bound object you can just cast the dataItem from the ListViewCommandEventArgs of the ItemCommand event. You don't need to retain the index or call FindControl at all.
Here is an example of how to get the bound Customer object.
ListView
<asp:ListView runat="server" id="Customers" ItemCommand="Customers_ItemCommand">
<LayoutTemplate>
<ul>
<asp:placeholder runat="server" id="itemPlaceholder" />
</ul>
</LayoutTemplate>
<ItemTemplate>
<li>
<asp:Button runat="server" id="Select" CommandName="Select" />
<%# Eval("Name")%>
</li>
</ItemTemplate>
</asp:ListView>
CodeBehind
public void Page_Load()
{
if (!Page.IsPostBack)
{
this.Customers.DataSource = GetCustomers();
this.Customers.DataBind();
}
}
public void Customers_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
if (e.Item.ItemType != ListViewItemType.DataItem)
return;
var customer = ((ListViewDataItem)e.Item).DataItem as Customer;
if (customer != null)
{
// Now work directly with the customer object.
Response.Redirect("viewCustomer.aspx?id=" + customer.Id);
}
}
}
Edit: In addtion when you cast the item to a ListViewDataItem, then you also expose a ((ListViewDataItem)e.Item).DataItemIndex property that might help you.

Categories