Get the current value of a label's text value - c#

I did search other similar questions, most of which had to do with jscript. I am having a difficult enough time trying to learn C#, so hopefully there is answer. I seems like I always get close to the answer only to find I have hit another hidden exception. What I am attempting to do is a work around for what must exist a more elegant way, but here it is: I have a check box, that when checked, changes Label1 text to "1" and unchecked changes Label1 text to "0". When the button on the page is clicked it sends data fields to a stored procedure. Even though I can see that the label value is either 1 or 0, the send to SP function always sends 'NULL' for Label1, which I assume is the default value for a blank label. So how do I get page to read the current value of the label when the button is clicked?
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-/W3C//DTD/ XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1-transitional.dtd">
<script runat="server">
public void InsertCard (object source, EventArgs e)
{
SqlDataSource1.Insert();
}
public void CheckBox1_CheckChanged (object source, EventArgs e)
{
Response.Write("");
if (CheckBox1.Checked == true)
{
Label1.Text = "1";
}
else
{
Label1.Text = "0";
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:sqldatasource
id="SqlDataSource1"
runat="server"
connectionstring="<%$ ConnectionStrings:DevTestConnectionString %>"
insertcommand="AddMember" InsertCommandType="StoredProcedure">
<insertparameters>
<asp:FormParameter Name="CardNumber" formfield="CardNumberBox" Type="int32" />
<asp:FormParameter Name="NameFirst" formfield="NameBox" Type="String" />
<asp:FormParameter Name="Valid" formfield="Label1" Type="string" />
</insertparameters>
</asp:sqldatasource>
<div>
<asp:Label ID="Label1" runat="server"></asp:Label>
<hr />
Last Name:<asp:TextBox id="NameBox" runat="server" Width="150px"></asp:TextBox>
<br>
Card Number:<asp:textbox id="CardNumberBox" runat="server" />
<br>
<asp:CheckBox ID="CheckBox1" runat="server" Text=" Valid" OnCheckedChanged="CheckBox1_CheckChanged" AutoPostBack="true" />
<br>
<asp:button id="Button1" runat="server" text="Add Card" onclick="InsertCard" />
</div>
</form>
</body>
</html>

Why used the label? Use the checkbox directly and set the datatype on the table column to bit. Replace the label to the below.
<asp:ControlParameter ControlID="CheckBox1" Name="Valid" PropertyName="Checked" Type="Boolean"/>

Related

Dropdownlist inside Updatepanel not passing selected item

I have a Gridview that has a hide/show panel. Inside the Panel there is a dropdown and a button. On button press I need the selected value of the dropdown, but I keep getting the first item, no matted what is selected.
I have been investigating the issue and it is to do with the panel control. If I place the dropdown outside the panel, everything works as intended. But dropdown only passes the first value when inside the panel.
Here is my code:
ASP Code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="DD.aspx.cs" Inherits="DD" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<title></title>
<script type="text/javascript">
$(document).on("click", '[src*=plus]', function () {
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
$(this).attr("src", "images/minus.png");
});
$(document).on("click", '[src*=minus]', function () {
$(this).attr("src", "images/plus.png");
$(this).closest("tr").next().remove();
})
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:constr %>" SelectCommand="SELECT * FROM [Requests]"></asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:constr %>" SelectCommand="SELECT [Name] FROM [Staff]"></asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="RequestID" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="RequestID" HeaderText="RequestID" InsertVisible="False" ReadOnly="True" SortExpression="RequestID" />
<asp:TemplateField>
<ItemTemplate>
<img runat="server" style="cursor: pointer" src="images/plus.png" />
<asp:UpdatePanel ID="pnlOrders" runat="server" Style="display: none" UpdateMode="Conditional">
<ContentTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2" DataTextField="Name" DataValueField="Name" AutoPostBack="true">
</asp:DropDownList>
<asp:Button runat="server" ID="test" OnClick="test_Click" />
</ContentTemplate> </asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
</body>
</html>
C# Code
protected void test_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
DropDownList referalDD = gvr.FindControl("DD1") as DropDownList;
string www = referalDD.SelectedItem.Text;
string qqq = referalDD.SelectedItem.Value;
}
Can anyone help me to solve this issue
Ok so I have found a work around / solution. Thanks to Niko for the placeholder suggestion. I got rid of this code:
<img runat="server" style="cursor: pointer" src="images/plus.png" />
and the related Jquery
$(document).on("click", '[src*=plus]', function () {
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
$(this).attr("src", "images/minus.png");
});
$(document).on("click", '[src*=minus]', function () {
$(this).attr("src", "images/plus.png");
$(this).closest("tr").next().remove();
})
Added a placeholder around the updatepanel and a Image button
<asp:ImageButton runat="server" ID="ShowHide" ImageUrl="~/images/plus.png" OnClick="ShowHide_Click" />
<asp:PlaceHolder ID="PlaceHolder1" runat="server" Visible="false">
And this code for the button click event.
protected void ShowHide_Click(object sender, EventArgs e)
{
ImageButton btn = (ImageButton)sender;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
PlaceHolder ph = gvr.FindControl("PlaceHolder1") as PlaceHolder;
if (btn.ImageUrl.ToString() == "~/images/plus.png")
{
ph.Visible = true;
btn.ImageUrl = "~/images/minus.png";
}
else
{
ph.Visible = false;
btn.ImageUrl = "~/images/plus.png";
}
}
Note: After further testing the whole issue was to do with UpdatePanel having this code Style="display: none" As soon as I removed this, everything worked. But I added the placeholder for by show/Hide feature.

Only allow one checkbox to be selected in gridview within modalpopup

I have a modal popup that has a gridview, this gridview has a number of rows, I only want the user to be able to select one row. So if they select another it will deselect the previous one.
I have tried a number of methods but can't get the oncheckedchanged event to fire.
Please can someone assist
Cheers
<asp:button id="btnShowPopupOW" style="display: none" runat="server" />
<asp:modalpopupextender id="mpeOW" behaviorid="mpeOW" runat="server" targetcontrolid="btnShowPopupOW"
popupcontrolid="pnlpopupOW" cancelcontrolid="imgOWCancel" backgroundcssclass="modalBackground" />
<asp:panel id="pnlpopupOW" runat="server" width="600px" style="display: none;" class="ModalPanel">
<div style="position: relative; min-height: 490px;">
<asp:UpdatePanel ID="upExisting" runat="server" ChildrenAsTriggers="true">
<ContentTemplate>
<table style="width: 600px;">
<tr height="25px">
<td>
<asp:Panel ID="pnlPrev" runat="server" Height="200px" ScrollBars="Auto" HorizontalAlign="Center">
<asp:GridView ID="grdPrevious" runat="server" ClientIDMode="Static" AutoGenerateColumns="false" Width="100%"
ShowFooter="false" ShowHeaderWhenEmpty="false" DataKeyNames="ID" >
<Columns>
<asp:BoundField DataField="dates" HeaderText="Dates" />
<asp:BoundField DataField="Prev" HeaderText="Previous" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="ChkSelect" runat="server" OnCheckedChanged="ChkSelect_OnCheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
</td>
</tr>
</table>
</ContentTemplate>
<Triggers>
</Triggers>
</asp:UpdatePanel>
</div>
</asp:panel>
with the following in the codebehind
protected void ChkSelect_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox activeCheckBox = sender as CheckBox;
foreach (GridViewRow rw in grdPrevious.Rows)
{
CheckBox chkBx = (CheckBox)rw.FindControl("ChkSelect");
if (chkBx != activeCheckBox)
{
chkBx.Checked = false;
}
else
{
chkBx.Checked = true;
}
}
}
You can do it like this. With single check box selection using jquery....
<ItemTemplate>
<asp:CheckBox ID="ChkSelect" runat="server" onclick="CheckOne(this)" />
</ItemTemplate>
function CheckOne(obj) {
var grid = obj.parentNode.parentNode.parentNode;
var inputs = grid.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
if (obj.checked && inputs[i] != obj && inputs[i].checked) {
inputs[i].checked = false;
}
}
}
}
you want to a single checked in check box . i think Using this you will be able to select only one check box at a time. Put the following java script code in the head section of the web page
<script type="text/javascript">
function SingleCheckboxCheck(ob)
{
var gridvalue = ob.parentNode.parentNode.parentNode;
var inputs = gridvalue.getElementsByTagName("input");
for(var i=0;i<inputs.length;i++)
{
if (inputs[i].type =="checkbox")
{
if(ob.checked && inputs[i] != ob && inputs[i].checked)
{
inputs[i].checked = false;
}
}
}
}
</script>
Here checkbox as a TemplateField of the GridView inside just call the above javascript function to make it single checkable.
onclick ="SingleCheckboxCheck(this)"
What you need is probably a (RadioButton)[http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.radiobutton(v=vs.110).aspx] instead of a CheckBox.
You can group the RadioButton's together which then allows the user to only select one item and automatically deselects the previous selected - or: exactly the behavior you want for your application.
This example code is taken from the linked MSDN Documentation. Note the GroupName attribute
<%# Page Language="C#" AutoEventWireup="True" %>
<!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>RadioButton Example</title>
<script language="C#" runat="server">
void SubmitBtn_Click(Object Sender, EventArgs e) {
if (Radio1.Checked) {
Label1.Text = "You selected " + Radio1.Text;
}
else if (Radio2.Checked) {
Label1.Text = "You selected " + Radio2.Text;
}
else if (Radio3.Checked) {
Label1.Text = "You selected " + Radio3.Text;
}
}
</script>
</head>
<body>
<h3>RadioButton Example</h3>
<form id="form1" runat="server">
<h4>Select the type of installation you want to perform:</h4>
<asp:RadioButton id="Radio1" Text="Typical" Checked="True" GroupName="RadioGroup1" runat="server" />
<br />
This option installs the features most typically used. <i>Requires 1.2 MB disk space.</i><br />
<asp:RadioButton id="Radio2" Text="Compact" GroupName="RadioGroup1" runat="server"/>
<br />
This option installs the minimum files required to run the product. <i>Requires 350 KB disk space.</i>
<br />
<asp:RadioButton id="Radio3" runat="server" Text="Full" GroupName="RadioGroup1" />
<br />
This option installs all features for the product. <i>Requires 4.3 MB disk space.</i>
<br />
<asp:button text="Submit" OnClick="SubmitBtn_Click" runat="server"/>
<asp:Label id="Label1" font-bold="true" runat="server" />
</form>

Using Select Command With a DDL

I'm having some problems with my code. Basically I want a DDL that has a list of values from a table sorted by the primary key. When an item is selected and a button is clicked, a Grid View shows the rest of the information about the respective record. I'll post the code I have now. For some reason, nothing appears in the DDL at all and I can't seem to figure out why.
<%# Page Language="C#" %>
<%# Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void Page_Load()
{
if (!Page.IsPostBack)
{
grv1.DataSource = srcCSC;
grv1.DataBind();
}
}
void btn1_click(object sender, EventArgs e)
{
DataSourceSelectArguments objSelectArg = new DataSourceSelectArguments();
DataView objView = (DataView)srcCSC.Select(objSelectArg);
srcCSC.Select(objSelectArg);
//rebind
grv1.DataSource = srcCSC;
grv1.DataBind();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
City:
<asp:DropDownList ID="ddlCity" runat="server" DataSourceID="srcCSC" DataTextField="City" DataValueField="City" /><br />
<asp:SqlDataSource
ID="srcCSC"
runat="server"
ConnectionString="<%$ ConnectionStrings:xyz1%>"
SelectCommand="Select City, CompanyName, ContactName, Relationship From CustomerSupplierCity Where City=#City">
<SelectParameters>
<asp:ControlParameter ControlID="ddlCity" Name="City" />
</SelectParameters>
</asp:SqlDataSource>
<br />
<br />
<asp:Button ID="btn1" Text="Select" runat="server"
OnClick="btn1_click" />
<asp:GridView ID="grv1" runat="server" AllowPaging="true" DataKeyNames="City,CompanyName,Relationship" />
</div>
</form>
</body>
</html>

Calling C# getter from UpdatePanel / javascript - never get updated data

I have this property in my code-behind.
public string LocationOptions
{
get { return Session["LocationOptions"].ToString(); }
set { Session["LocationOptions"] = value; }
}
On the front-end, I have this javascript.
<script type="text/javascript">
function pageLoad(sender, args) {
InitLocationsAutoComplete();
}
</script>
<asp:UpdatePanel ID="upScript" runat="server">
<ContentTemplate>
<script type="text/javascript">
function InitLocationsAutoComplete() {
var locationsJson = '<%= LocationOptions %>';
alert(locationsJson);
}
</script>
</ContentTemplate>
</asp:UpdatePanel>
I'm setting a breakpoint on my getter and setter in the C# code.
I'm using MVP and the setter gets called from a presenter.
On first page load, things work as expected. The breakpoint on the setter gets hit first. Then the breakpoint on the getter. Finally, I get a javascript alert with the value I expect to see.
I'm running into problems on partial postbacks that are triggered by other update panels. On those, my setter breakpoint hits with a new value. My getter breakpoint gets hit next, and if I quick watch Session["LocationOptions"] I see the new value there. But when I get the javascript alert, it still alerts the initial value from the first page load.
If it still calls the property in C#, then I don't see why the updated value doesn't come through to the javascript. Why am I stuck with the initial value from first page load?
As far as I know, javascript in the partially updated content is not re-executed/re-evaluated. My understanding is that the partial update will essentially edit the DOM to update a part of the page, but this does not allow one to dynamically upate javascript on the page. You can use ScriptManager.RegisterClientScriptBlock on the server-side to register your updated javascript during the partial postback.
I've had the same issue in the past.
The issue is due to the fact that the dom is only partially updated, i've personally corrected this by registering the script in the ScriptManager.
An example of this is here: ScriptManager.RegisterClientScriptBlock Method (Control, Type, String, String, Boolean)
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_PreRender(object sender, EventArgs e)
{
string script = #"
function ToggleItem(id)
{
var elem = $get('div'+id);
if (elem)
{
if (elem.style.display != 'block')
{
elem.style.display = 'block';
elem.style.visibility = 'visible';
}
else
{
elem.style.display = 'none';
elem.style.visibility = 'hidden';
}
}
}
";
ScriptManager.RegisterClientScriptBlock(
this,
typeof(Page),
"ToggleScript",
script,
true);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>ScriptManager RegisterClientScriptInclude</title>
</head>
<body>
<form id="Form1" runat="server">
<div>
<br />
<asp:ScriptManager ID="ScriptManager1"
EnablePartialRendering="true"
runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1"
UpdateMode="Conditional"
runat="server">
<ContentTemplate>
<asp:XmlDataSource ID="XmlDataSource1"
DataFile="~/App_Data/Contacts.xml"
XPath="Contacts/Contact"
runat="server"/>
<asp:DataList ID="DataList1" DataSourceID="XmlDataSource1"
BackColor="White" BorderColor="#E7E7FF" BorderStyle="None"
BorderWidth="1px" CellPadding="3" GridLines="Horizontal"
runat="server">
<ItemTemplate>
<div style="font-size:larger; font-weight:bold; cursor:pointer;"
onclick='ToggleItem(<%# Eval("ID") %>);'>
<span><%# Eval("Name") %></span>
</div>
<div id='div<%# Eval("ID") %>'
style="display: block; visibility: visible;">
<span><%# Eval("Company") %></span>
<br />
<a href='<%# Eval("URL") %>'
target="_blank"
title='<%# Eval("Name", "Link to the {0} Web site") %>'>
<%# Eval("URL") %></a>
</asp:LinkButton>
<hr />
</div>
</ItemTemplate>
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<SelectedItemStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<AlternatingItemStyle BackColor="#F7F7F7" />
<ItemStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
</asp:DataList>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
i hope this helps.

How to fetch data from gridview row that is selected?

I'm trying to fetch the data from the gridview according to the row I select for deletion.
I tried this,
string fileName = grdUploadedFiles.Rows[e.RowIndex].Cells[2].ToString();
but it shows the string,
System.Web.UI.WebControls.DataControlFieldCell
What exactly can I do to fetch the filename that I have inserted to the gridview.
Also, this field is not the DataKey.
If your cell not contain any control like label then try this
string fileName = grdUploadedFiles.Rows[e.RowIndex].Cells[2].Text;
You should be calling .Text for the value, per MSDN documentation.
Generally speaking .ToString is overridden by default for Value types. Reference types generally don't override .ToSting with their "values" (what you would commonly access when calling that class).
Here is an example from MSDN:
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void CustomersGridView_RowDeleting
(Object sender, GridViewDeleteEventArgs e)
{
TableCell cell = CustomersGridView.Rows[e.RowIndex].Cells[2];
if (cell.Text == "Beaver")
{
e.Cancel = true;
Message.Text = "You cannot delete customer Beaver.";
}
else
{
Message.Text = "";
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>GridView RowDeleting Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>
GridView RowDeleting Example
</h3>
<asp:Label ID="Message" ForeColor="Red" runat="server" />
<br />
<asp:GridView ID="CustomersGridView" runat="server"
DataSourceID="CustomersSqlDataSource"
AutoGenerateColumns="False"
AutoGenerateDeleteButton="True"
OnRowDeleting="CustomersGridView_RowDeleting"
DataKeyNames="CustomerID,AddressID">
<Columns>
<asp:BoundField DataField="FirstName"
HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName"
SortExpression="LastName" />
<asp:BoundField DataField="City" HeaderText="City"
SortExpression="City" />
<asp:BoundField DataField="StateProvince" HeaderText="State"
SortExpression="StateProvince" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="CustomersSqlDataSource" runat="server"
SelectCommand="SELECT SalesLT.CustomerAddress.CustomerID,
SalesLT.CustomerAddress.AddressID,
SalesLT.Customer.FirstName,
SalesLT.Customer.LastName,
SalesLT.Address.City,
SalesLT.Address.StateProvince
FROM SalesLT.Customer
INNER JOIN SalesLT.CustomerAddress
ON SalesLT.Customer.CustomerID =
SalesLT.CustomerAddress.CustomerID
INNER JOIN SalesLT.Address ON SalesLT.CustomerAddress.AddressID =
SalesLT.Address.AddressID"
DeleteCommand="Delete from SalesLT.CustomerAddress where CustomerID =
#CustomerID and AddressID = #AddressID"
ConnectionString="<%$ ConnectionStrings:AdventureWorksLTConnectionString %>">
<DeleteParameters>
<asp:Parameter Name="AddressID" />
<asp:Parameter Name="CustomerID" />
</DeleteParameters>
</asp:SqlDataSource>
</form>
</body>
</html>

Categories

Resources