How to get selected radio button text in datalist ? - c#

In below data list represents set of question's and answer, How to check whether the user selected right answer radio button or not when the user clicks on submit button using javascript ?
the answer is stored in database.
Datalist:
<asp:DataList ID="DataList1" runat="server" DataKeyField="Qno"
DataSourceID="SqlDataSource1">
<ItemTemplate>
Qno:
<asp:Label ID="QnoLabel" runat="server" Text='<%# Eval("Qno") %>' />
<br />
Question:
<asp:Label ID="QuestionLabel" runat="server" Text='<%# Eval("Question") %>' />
<br />
<asp:RadioButton ID="RadioButton1" runat="server" Text='<%# Eval("Ans1") %>' />
<br />
<asp:RadioButton ID="RadioButton2" runat="server" Text='<%# Eval("Ans2") %>' />
<br />
<asp:RadioButton ID="RadioButton3" runat="server" Text='<%# Eval("Ans3") %>' />
<br />
<asp:RadioButton ID="RadioButton4" runat="server" Text='<%# Eval("Ans4") %>' />
<br />
<asp:Button ID="Button2" runat="server" Text="Submit" />
<br />
</ItemTemplate>
</asp:DataList>

Provide a CommandName parameter for the Button2 in the DataList: CommandName="Validate"
Add the OnItemCommand event for the DataList1: *OnItemCommand="DataList1_OnItemCommand"*
In the code behind, fill-in the *DataList1_OnItemCommand* event actions:
protected void DataList1_OnItemCommand(object sender, DataListCommandEventArgs e)
{
if (String.Equals(e.CommandName, "Validate"))
{
DataListItem dataItem = (DataListItem )e.Item;
RadioButton rbtn1 = (RadioButton)dataItem.FindControl("RadioButton1");
RadioButton rbtn2 = (RadioButton)dataItem.FindControl("RadioButton2");
RadioButton rbtn3 = (RadioButton)dataItem.FindControl("RadioButton3");
RadioButton rbtn4 = (RadioButton)dataItem.FindControl("RadioButton4");
// Code to check which radio button was checked.
if(rbtn1 != null && rbtn1.Checked)
{
}
else if(rbtn2 != null && rbtn2.Checked)
{
} //Perform these for the remaining two check boxes
}
}
Take required actions based on which check box is checked.

Related

Why Rowcommand event of a gridview is not getting fired ?

I am facing a kind of weird problem.
Problem:
When I click a link button inside a grid view then RowCommand event of a grid view is getting fired when deployed on a localhost but not when deployed on the IIS i.e. client system. I have also tried a link button inside grid view but that's also not getting fired.
Solution: (Temporary)
When I disabled ValidateRequest on the top of the .aspx page. It worked.
What should I do?
So what can be the possible solution for it? I have googled but nothing good came up.
Code:
<asp:GridView ID="gvAppliedWorks" runat="server" OnRowCommand="gvAppliedWorks_RowCommand" AutoGenerateColumns="false" DataKeyNames="AppliedWorkID, ContractorID" EmptyDataText="No Data Found"
CssClass="table table-responsive table-bordered table-striped" OnRowDataBound="gvAppliedWorks_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Form No">
<ItemTemplate>
<asp:Literal ID="liFormNo" runat="server" Text='<% #Eval("FormNo")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Company Name">
<ItemTemplate>
<asp:Literal ID="liCompanyName" runat="server" Text='<% #Eval("Name")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Financial Bid">
<ItemTemplate>
<asp:Label ID="txtBidAmount" runat="server" CssClass="control-label" Text='<% # string.Format("{0:n2}", Eval("FinancialMoney").ToString())%>' />
%
<asp:Label ID="ddlBidPer" runat="server" CssClass="control-label" Text='<%# Eval("AboveBelow").ToString() %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Awarded Percentage">
<ItemTemplate>
<div class="pull-left">
<asp:HiddenField ID="hdnIsAwarded" Value='<%# Eval("IsAwarded") %>' runat="server" />
<asp:TextBox ID="txtAwardedBid" Text='<%#Eval("AwardedBid")%>' Style="width: 70px !important;" runat="server" CssClass="form-control"></asp:TextBox>
</div>
<div class="pull-left" style="margin-top: 7px">
% <%# Eval("AboveBelow").ToString() %>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remarks">
<ItemTemplate>
<asp:TextBox ID="txtRemarks" Text='<%#Eval("Remarks")%>' runat="server" CssClass="form-control"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Award Tender">
<ItemTemplate>
<asp:LinkButton ID="lnkAward" runat="server"
CommandArgument='<%# Eval("AppliedWorkID") %>' CommandName="award"
CssClass="btn btn-sm btn-danger" Enabled='<%# Convert.ToBoolean(Eval("IsBlackList")) == true ? false: true %>'
Visible='<%# Convert.ToBoolean( Eval("IsAwarded"))== false? true:false%>' CausesValidation="false" Text="Award"></asp:LinkButton>
<ajax:ConfirmButtonExtender ID="cbe" runat="server" DisplayModalPopupID="mpe" TargetControlID="lnkAward">
</ajax:ConfirmButtonExtender>
<ajax:ModalPopupExtender ID="mpe" runat="server" PopupControlID="pnlPopup" TargetControlID="lnkAward" OkControlID="btnYes"
CancelControlID="btnNo" BackgroundCssClass="modalBackground">
</ajax:ModalPopupExtender>
<asp:Panel ID="pnlPopup" runat="server" CssClass="modalPopup" Style="display: none">
<div class="header">
Confirmation
</div>
<div class="body">
Are you sure to Award this Work?
</div>
<div class="Popupfooter" align="right">
<asp:Button ID="btnYes" CssClass="btn btn-sm btn-danger" runat="server" Text="Yes" />
<asp:Button ID="btnNo" CssClass="btn btn-sm btn-primary" runat="server" Text="No" />
</div>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText='Action'>
<ItemTemplate>
<asp:LinkButton ID="btnBlackList" runat="server" OnClick="btnBlackList_Click" Visible='<%# Convert.ToBoolean( Eval("IsAwarded"))== false? true:false%>' Enabled='<%# Convert.ToBoolean(Eval("IsBlackList")) == true ? false: true %>' Text='Defective'
CssClass="" ToolTip="Blacklist"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
**.cs**
protected void gvAppliedWorks_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
// GridViewRow gr = ((GridViewRow)((Control)sender).Parent.Parent);
if (e.CommandName == "award")
{
GridViewRow gr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
int AppliedWorkID = e.CommandArgument.ToInt32(); //gvAppliedWorks.DataKeys[gr.RowIndex].Value.ToInt32();
TextBox txtAwardedBid = gr.FindControl("txtAwardedBid") as TextBox;
TextBox txtRemarks = gr.FindControl("txtRemarks") as TextBox;
Label txtBid = gr.FindControl("txtBidAmount") as Label;
Label lblAboveBelow = gr.FindControl("ddlBidPer") as Label;
string AboveBelow = lblAboveBelow.Text;
Decimal BidAmount = txtBid.Text.ToDecimal();
if (String.IsNullOrEmpty(txtRemarks.Text))
{
Utility.Msg_Error(this.Master, "Remarks Required!!!");
return;
}
Decimal AwardedBid = string.IsNullOrEmpty(txtAwardedBid.Text.Trim()) ? 0 : txtAwardedBid.Text.Trim().ToDecimal();
string Remarks = txtRemarks.Text;
if (AwardedBid != BidAmount)
{
Utility.Msg_Error(this.Master, "Financial Bid must be equal to Awarded Percentage");
return;
}
if (ClsTender.IsReceivedSubMainOffice(AppliedWorkID, LoginUserID, AwardedBid, Remarks, BidAmount, AboveBelow))
{
Utility.Msg_Success(this.Master, "Work Awarded Successfully!!!");
fill_gvAppliedWorks(labNitNo.Text.Replace("NIT No :", "").ToInt32(), labWorkNo.Text.Replace("Work No :", "").ToInt32());
}
}
}
catch (Exception ex)
{
Utility.Msg_Error(Master, ex.Message);
}
}
It sounds like your page is trying to submit what it thinks is potentially dangerous content if setting the ValidateRequest = false solves the issue. Is it possible that one of the controls on your page is sending html or something like that?
If one of your controls needs to send HTML then you can overcome this by adding an attribute to your model.
[AllowHtml]
[Required]
public string article_content { get; set; }
This will allow html to be entered into the control.

setting CSS class to selected ASP.NET Listview Item

I have a listview which I want highlight the items on click.
Using the below code, I could set the CSS class. But the foreach loop doesn't clear the css class set before.
<asp:ListView ID="ListView2" runat="server" SelectedIndex="0" onitemcommand="ListView2_ItemCommand">
<ItemTemplate>
<asp:Panel ID="Panel8" runat="server" CssClass="left-listitem-div">
<asp:Image ID="Image1" runat="server" AlternateText="User Icon" ImageUrl='<%# Eval("UserType").ToString() == "AD_USER" ? "Images/icons/ldapuser32px.png" : "Images/icons/user32px.png" %>' CssClass="list-group-icon" />
<asp:Label ID="ListUserID" runat="server" Text ='<%#Eval("UserID") %>' CssClass="list-group-id" style="display:none;" />
<asp:LinkButton ID="ListFullName" runat="server" Text='<%#Eval("FullName") %>' CssClass="list-group-name" CommandName="select" CommandArgument = '<%# Eval("UserID") %>' Font-Underline="False" ForeColor="Black" Width="130" Height="30" />
<asp:Label ID="ListUserName" runat="server" Text='<%#Eval("UserName") %>' CssClass="list-group-username" style="display:none;" />
<asp:Label ID="ListUserType" runat="server" Text='<%#Eval("UserType") %>' CssClass="list-group-usertype" style="display:none;" />
<asp:Label ID="ListUserEnabled" runat="server" Text='<%#Eval("Enabled") %>' CssClass="list-group-enabled" style="display:none;" />
<asp:Label ID="ListUserDescription" runat="server" Text ='<%#Eval("Description") %>' CssClass="list-group-descri" style="display:none;" />
</asp:Panel>
</ItemTemplate>
</asp:ListView>
The Codebehind is below.
I used SelectedItemTemplate, but Listview selectedIndex is not changing.
If I set the selectedIndex on ItemCommand event, Its affecting only at the next postback.
protected void ListView2_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.Item.FindControl("Panel8") != null && e.Item.FindControl("Panel8") is Panel)
{
foreach (ListViewItem li in ListView2.Items)
{
Panel lipp = (Panel)e.Item.FindControl("Panel8");
lipp.CssClass = "left-listitem-div";
}
Panel pp = (Panel)e.Item.FindControl("Panel8");
pp.CssClass = "left-listitem-div selected";
}
}
Ok, don't change the event, because you use commandEventargs.
Just set the SelectIndex of the listview and then change the css for that item.
protected void ListView2_ItemCommand(object sender, ListViewCommandEventArgs e)
{
(sender as ListView).SelectedIndex = e.Item.DataItemIndex;
(e.Item.FindControl("Panel8") as Panel).CssClass += "SelectedCss";
}
In the loop you alwas refer to the currently selected item, that's your problem.
Change the loop to this: --> li
foreach (ListViewItem li in ListView2.Items)
{
Panel lipp = (Panel)li.FindControl("Panel8");
lipp.CssClass = "left-listitem-div";
}

How to get radio button checked value in Footer Template DataList?

I"m using DataList. in my FooterTemplate I add a radio button I I want check it. but it always return false.
This is my code
<asp:DataList ID="dlDelivery" OnItemDataBound="dlDelivery_DataBound" RepeatColumns="1" RepeatDirection="Vertical" Width="300" runat="server">
<ItemTemplate>
<asp:RadioButton ID="rdoDel" GroupName="aaa" OnCheckedChanged="rdoOther_Changed" AutoPostBack="true" runat="server" />
<asp:Label ID="lblDel1" Text='<%# Eval("Street") %>' runat="server" /><br />
<asp:Label ID="lblDel2" Text='<%# Eval("Suburb") %>' runat="server" />
<span class="clear" />
</ItemTemplate>
<FooterTemplate>
<asp:RadioButton ID="rdoOther" Text="Other" OnCheckedChanged="rdoOther_Changed" AutoPostBack="true" GroupName="aaa" runat="server" />
a
<br class="clear" />
</FooterTemplate>
</asp:DataList>
I check the rdoOther check like this
RadioButton rdoOther = (RadioButton)dlDelivery.Controls[dlDelivery.Controls.Count - 1].Controls[0].FindControl("rdoOther");
if (rdoOther.Checked = true ) // this always fales
{
}
How to fix it?
Try this
foreach (DataListItem item in dlDelivery.Items)
{
if (item.ItemType == ListItemType.Footer)
{
RadioButton rdoOther = (RadioButton)item.FindControl("rdoOther");
}
}
Simply search the radio button in e.Item:
protected void dlDelivery_DataBound(object sender, DataListItemEventArgs e)
{
RadioButton rdoOther = e.Item.FindControl("rdoOther") as RadioButton;
//rdoOther will be null if ListItemType is not footer.
if (rdoOther !=null && rdoOther.Checked)
{
// Do your tasks
}
}

Hide and Display of TabPanel in TabContainer

I'm trying to hide the TabPanel4 when the application start, then when user select specific item from the dropdownlist it then display the TabPanel4 out for the user. Below is the code I used, not sure why it not working. Do help me take a look at my code see which part did I do wrongly. Thanks!
Aspx
<asp:TabContainer ID="TabContainer1" runat="server" Height="75%" Width="100%" UseHorizontalStripPlacement="true"
ActiveTabIndex="0" OnDemand="true" AutoPostBack="true" TabStripPlacement="Top" ScrollBars="Auto">
<asp:TabPanel ID="TabPanel1" runat="server" HeaderText="Incident Information" Enabled="true" ScrollBars="Auto" OnDemandMode="Once">
<ContentTemplate>
<table width="100%">
<tr>
<td>
<b>Type of crime:</b>
<asp:DropDownList ID="ddlToC" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlToC_SelectedIndexChanged">
<asp:ListItem>Accident</asp:ListItem>
<asp:ListItem>Theft</asp:ListItem>
<asp:ListItem>Robbery</asp:ListItem>
<asp:ListItem>Housebreaking</asp:ListItem>
<asp:ListItem>Fraud</asp:ListItem>
<asp:ListItem>Loan Shark</asp:ListItem>
</asp:DropDownList>
<br />
</td>
</tr>
</table>
</ContentTemplate>
</asp:TabPanel>
<asp:TabPanel ID="TabPanel4" runat="server" HeaderText="Property" Enabled="true" ScrollBars="Auto" OnDemandMode="Once" Visible="false">
<ContentTemplate>
Is there any property lost in the incident?
<asp:RadioButton ID="rbPropertyYes" runat="server" GroupName="rbGroup3" Text="Yes" AutoPostBack="True" />
<asp:RadioButton ID="rbPropertyNo" runat="server" GroupName="rbGroup3" Text="No" AutoPostBack="True" />
<br />
<br />
<asp:Label ID="Label4" runat="server" Text="Describe what was lost in the incident." Visible="False"></asp:Label>
<br />
<br />
<asp:TextBox ID="txtProperty" runat="server" Height="75px" TextWrapping="Wrap" TextMode="MultiLine" Width="400px" Visible="False"/>
<br />
<br />
<asp:Label ID="Label5" runat="server" Text="You have " Visible="False"></asp:Label><asp:Label ID="lblCount3" runat="server" Text="500" Visible="False"></asp:Label> <asp:Label ID="Label6" runat="server" Text=" characters left." Visible="False"></asp:Label>
</ContentTemplate>
</asp:TabPanel>
</asp:TabContainer>
Code behind
protected void ddlToC_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlToC.SelectedValue.Equals("Theft"))
{
TabPanel4.Visible = true;
}
else if (ddlToC.SelectedValue.Equals("Robbery"))
{
TabPanel4.Visible = true;
}
else if (ddlToC.SelectedValue.Equals("Housebreaking"))
{
TabPanel4.Visible = true;
}
else if (ddlToC.SelectedValue.Equals("Fraud"))
{
TabPanel4.Visible = true;
}
}
To add on: even I take away the Visible="false" from the aspx page and set it in code behind page under Page_Load it don't work, it still don't appear when I select the item in the dropdownlist. Also tried using TabContainer1.Tabs[3].Visible = false / true; to hide or display it but it also don't seem to work.
ddlToC is not handling SelectedIndexChanged.
Change your markup to this:
<asp:DropDownList ID="ddlToC" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlToC_SelectedIndexChanged">

Data lost in the postback

I need a way for a piece of data to presist across postbacks. Is there a way besides, cookies, and sessions?
I've got a listbox, when clicked, the selected index changed event takes a session which contains user id and feeds it to a method that fetches user's name, etc. Then I use FindControl method to locate a button inside the form view. I set the button's text property with data just fetched such as first and last name.
It works on the initial load, but if I click on other records in the listbox second time the text property is not set.
I did not write this code - I'm trying to make chages.
Here is the list box:
<asp:ListBox ID="lbxUpcommingEvents" runat="server" DataSourceID="odsUpcommingEvents"
Rows="6" DataTextField="Title" DataValueField="id" AutoPostBack="true"
Width="206px" OnSelectedIndexChanged="lbxUpcommingEvents_OnSelectedIndexChanged" />
Listbox'x on selected index changed:
protected void lbxUpcommingEvents_OnSelectedIndexChanged(object sender, EventArgs e)
{
pnlEventsSignUp.Visible = true;
string _selectedItemValue = lbxUpcommingEvents.SelectedValue.ToString();
LoadName();
}
protected void LoadName()
{
MembershipUser user = Membership.GetUser();
DataSetTableAdapters.MemberInfoTableAdapter da = new DataSetTableAdapters.MemberInfoTableAdapter();
Guid _memberId = Guid.Empty;
_memberId = new Guid(Session["myId"].ToString());
DataSet.MemberInfoDataTable dt = da.GetMember(_memberId);
if (dt.Rows.Count == 1)
{
DataSet.MemberInfoRow mr = dt[0];
RolloverLink rlnkSignUp = (RolloverLink)(fvEventSignUp.FindControl("rlnkSignUp"));
rlnkSignUp.Text = "I, " + mr.firstname + " " + mr.lastname + " will be attending this event.";
}
}
Here is markup for the form view where I set the RolloverLinkButton's text property.
<asp:Panel runat="server" ID="pnlEventsSignUp" visible="false">
<div class="dashedline" ></div>
<asp:FormView ID="fvEventSignUp" runat="server" DataSourceID="SqlDataSource1"
DataKeyNames="id" Width="100%" >
<ItemTemplate>
<h2>
<asp:Label Text='<%# Eval("title") %>' runat="server" ID="titleLabel" />
</h2>
<div class="itemdetails">
<br />
location:
<h3>
<asp:Label ID="locationLabel" runat="server" Text='<%# ShowLocationLink(Eval("locationname"),Eval("location")) %>' />
</h3>
<p>
<asp:Label Text='<%# Eval("starttime","{0:D}") %>' runat="server" ID="itemdateLabel" CssClass="GeneralText" />
<asp:Label Text='<%# ShowDuration(Eval("starttime"),Eval("endtime")) %>' runat="server" ID="Label1" CssClass="GeneralText" />
</p>
</div>
<div class="downloadevent">
<a href="#">
<img src="images/icon_download_event.gif" alt="Download this event to your personal calendar"
width="15" height="26" /></a><a href='<%# "events_download.ashx?EventID=" + Convert.ToString(Eval("id")) %>'>Add
this event to your personal calendar</a>
</div>
<Club:ImageThumbnail ID="thumb1" runat="server" ImageSize="Large" PhotoID='<%# Eval("photo") %>' />
<p>
<asp:Label Text='<%# Eval("description") %>' runat="server" ID="descriptionLabel" />
</p>
<div class="dashedline" ></div>
<asp:Panel ID="panel1" runat="server" CssClass="actionbuttons" Visible='<%#User.IsInRole("Administrators") %>'>
<table border="0" cellpadding="2" cellspacing="2">
<tr>
<td>
<asp:Label runat="server" ID="Label2" Text="Action<br />Required" Width="80px" />
</td>
<td>
<img src="images/RedArrow.jpg" alt="Red Arrow Right" />
</td>
<td>
<asp:CheckBox runat="server" ID="cbxCert" Height="30px" Text="Check to Confirm Attendance" /><br />
<asp:CustomValidator runat="server" ID="rfvConfirm"
ErrorMessage="You must check the box to continue" Font-Bold="true"
ForeColor="#cc0000" ClientValidationFunction="ensureChecked" /> <br />
<Club:RolloverLink ID="rlnkSignUp" runat="server"
/>
</td>
</tr>
</table>
</asp:Panel>
</ItemTemplate>
</asp:FormView>
</asp:Panel>
You can use ViewState. Since you are dynamically looking up the button, setting a property is quicker and we can then let Asp.Net find the button and set its text via one of the two methods I explain below:
public string rlnkSignUpText
{
get { return Convert.ToString(ViewState["rlnkSignUpText"] ?? "default value"); }
set { ViewState["rlnkSignUpText"] = value; }
}
Replace your code that searches for the button and assigns the text with:
rlnkSignUpText = "I, " + mr.firstname + " " + mr.lastname + " will be attending this event.";
Then use one of these methods to set the text to the control:
1) Use the control's OnPreRender event:
To render it, add OnPreRender="rlnkSignUp_PreRender" to your xaml like this:
<Club:RolloverLink ID="rlnkSignUp" runat="server" OnPreRender="rlnkSignUp_PreRender" />
Then in your codebehind:
protected void rlnkSignUp_PreRender(object sender, EventArgs e)
{
RolloverLink rlnkSignUp = (RolloverLink)sender;
rlnkSignUp.Text = rlnkSignUpText;
}
2) Bind the property and control together:
Instead of using the control's PreRender you can bind to the property with:
<Club:RolloverLink ID="rlnkSignUp" runat="server" Text='<%# rlnkSignUpText %>' />
You then need to call DataBind in your Page_PreRender() like so:
void Page_PreRender(object sender, EventArgs e)
{
DataBind();
}
Have you enabled ViewState in the control.
Enable View State

Categories

Resources