I want to access label value in code behind page - c#

I want to access label value in code behind page.
int a = int.Parse(Label5.Text);
if (a <= 10)
{
Label5.BackColor = System.Drawing.Color.Red;
}
<asp:Label CssClass="txtStock" ID="Label5" runat="server" Text='<%# Eval("Pquant") %>'></asp:Label>
I'm not able to access Label5 in code behind page as it doesn't exist.
I want to fetch Label5 value and store it in a variable.
Label5 is taken inside datalist control

You can't access Label5 in codebehind because it's part of a datacontrol like FormView, GridView, Repeater or someting. So this Label doesn't exist only once - it exists in every item of your data control.
If you want to set your BackColor dynamicly you can do it in the Databinding method (e.g. GridView)
protected void YourGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label Label5 = (Label)e.Row.FindControl("Label5");
if (int.Parse(Label5.Text) <= 10)
{
Label5.BackColor = System.Drawing.Color.Red;
}
}
}
or do directly in the Label:
<asp:Label CssClass="txtStock" ID="Label5" runat="server" Text='<%# Eval("Pquant") %>'
BackColor='<%# int.Parse(Eval("Pquant")) <= 10 ? System.Drawing.Color.Red : System.Drawing.Color.Black %>'
></asp:Label>

Related

get selected value by drop down list in a repeater by CommandArgument of link button

I have a repeater that in it has one dropdown list and one linkbutton.
I want to get the selected value of the dropdown list by CommandArgument in linkbutton, but it just knows default value of dropdown list.
My code :
<asp:Repeater runat="server" ID="Repeater1" OnItemDataBound="Page_Load2"OnItemCommand="list_ItemCommand" >
<ItemTemplate>
<asp:DropDownList ID="dlPricelist" CssClass="width100darsad dropdownlist" runat="server" AutoPostBack="true" ViewStateMode="Enabled" >
</asp:DropDownList>
<asp:LinkButton ID="btnAddToCart" runat="server" class="btn btn-success btnAddtoCardSinglepage" CommandArgument='<%#Eval("id") %>' CommandName="addtocard">اضافه به سبد خرید</asp:LinkButton>
<asp:Label ID="xxxxxx" runat="server" Text="Label"></asp:Label>
</ItemTemplate>
</asp:Repeater>
Code behind:
protected void Page_Load2(object sender, RepeaterItemEventArgs e)
{
if (!IsPostBack)
{
string id = Request.QueryString["id"].ToString();
DataSet dsselectcategory = BLLTour.left3join(id.Trim().ToString());
var dlPricelist = (DropDownList)e.Item.FindControl("dlPricelist");
dlPricelist.DataSource = dsselectcategory.Tables[0];
dlPricelist.DataTextField = "pricelistPrice";
dlPricelist.DataValueField = "priceid";
dlPricelist.DataBind();
}
}
protected void list_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "addtocard")
{
foreach (RepeaterItem dataItem in Repeater1.Items)
{
Label xxxxxx = (Label)e.Item.FindControl("xxxxxx");
LinkButton btnAddToCart = (LinkButton)e.Item.FindControl("btnAddToCart");
xxxxxx.Text = ((DropDownList)dataItem.FindControl("dlPricelist")).SelectedItem.Text; //No error
}
}
}
I don't know how I should fix it.
You are using very old technology to show data that's not appropriate.
But if you are serious to use it, you must use FindControll method in ItemTemplate of your repeater control. You should find dropdownlist first, and then cast it to a object to be able to use it's value.

Recover current value in checkBox during gridView Editing - WebForm C#

I have a simple checkBox in Editable gridView :
<asp:TemplateField HeaderText="Editable">
<ItemTemplate>
<asp:Label runat="server" Text="<%# Item.IsEditable %>" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="CheckBoxEditable " runat="server" Text="Editable"></asp:CheckBox>
</EditItemTemplate>
</asp:TemplateField>
When I click on edit button in the row, I would like that checkBox is already checked if value is true. (IsEditable is a boolean)
Text Field is easy because I have a BindItem on Text property in EditItemTemplate. But it's not the same for checkBox or dropdownlist
GridView
I use a UpdateItem Method to update my data in database. I tried a small condition to check my checkBox but it does'nt work.
public void GridViewRisquesAggravants_UpdateItem(IndexViewModel item)
{
try
{
if (ModelState.IsValid)
{
CheckBox chbEdit = (CheckBox)GridView.Rows[this.GridView.EditIndex].FindControl("CheckBoxEditable")
if (item.IsEditable)
chbEdit.Checked = true;
new TypeService().Update(new Type
{
IsEditable = item.IsEditable,
});
this.GridView.DataBind();
}
}
catch
{
throw;
}
}
It makes sense because I am not in the right function to declare this. But I just have 3 methods in my webform.
SelectMethod="GridView_GetData"
UpdateMethod="GridView_UpdateItem"
DeleteMethod="GridView_DeleteItem"
Where can I do this?
(And I have the same problem with datas on dropdownList. I don't know where I recover current value during editing)
Thanks in advance
(Sorry I am beginner about webforms and my english is not perfect)
Evy
use the following code instead for checkbox declaration in edit template
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Convert.ToBoolean("true") %>' />
CheckBox chbx = GridView1.HeaderRow.FindControl("CheckBoxEditable") as CheckBox;
if (chbx != null && chbx.Checked)
{
//code here
}
else
{
//else condtion
}
hope this helps
Where can I do this?
Try it in RowDataBound event:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox chbEdit = (CheckBox)e.Row.FindControl("CheckBoxEditable");
string value = ((Label)e.Row.FindControl("lblID")).Text;
if (value=="True")
chbEdit.Checked = true;
else
chbEdit.Checked = false;
}
}
Note: Don't forget to add OnRowDataBound in GrindView <asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" >
I added the property Checked=<%# BindItem.IsEditable %> on CheckBox Control and it works perfectly.

how to find a label in the itemtemplate on gridview?C# ASP.NET

I have a GridView that bound some data from DB and have a label in the ItemTemplate and EditTextbox in the EditItemTemplate they are in the same TemplateField. In the GridView some user has no data in somewhere field, If I want to insert a data for these user, I need to find GirdView label first and var the edittextbox, when updating I can Compare the value of them , such as the edittextbox value not equals to labeldata value then insert,
but I can't find the value of the label when rowupdating or databound of gridview
how can i do it ?
I have try
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
int rowCount = GridView1.Rows.Count;
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (rowCount >= 1)
{
Label lbDA_TEL_HK_NO = ((Label)e.Row.FindControl("lblKM_TEL"));
Session["DA_TEL_HK_NO"] = lbDA_TEL_HK_NO.Text;
}
}
}
It can find all the gridview data but not which I selected
P.S I'm a newbie, please help me
<asp:TemplateField ItemStyle-Width = "150px" HeaderText = "香港內線">
<ItemTemplate>
<asp:Label ID="lblHK_TEL" runat="server"
Text='<%# Eval("[DA_TEL_HK_NO]")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtHK_TEL" runat="server" onkeyup="this.value=this.value.replace(/[^0-9]/g,'')" MaxLength="3"
Text='<%# Eval("[DA_TEL_HK_NO]")%>'></asp:TextBox>
</EditItemTemplate>
You can try something like this for read all rows in grid view:
for (var i = 0; i < GridView1.Rows.Count; i++)
{
var label = GridView1.Rows[i].FindControl("lblKM_TEL") as Label;
if (label != null)
{
// Manipulate label control
}
}
Or you can gets label from selected row:
var label = GridView1.SelectedRow.FindControl("lblKM_TEL") as Label;
if (label != null)
{
// Manipulate label control
}
From your aspx markup you are using the wrong label id .
you need yo use this label id lblHK_TEL
You code looks as follows after changes
Label lbDA_TEL_HK_NO = ((Label)e.Row.FindControl("lblHK_TEL"));

Set value of button based on returned value

I am using a GridView in asp.net.
The first column is a list of button controls -
<ItemTemplate>
<asp:Button ID="statusButton" runat="server" Text="Select"
OnClick="statusButton_CheckedChanged" />
</ItemTemplate>
However I want to modify the background color and Text values of this button on data bind based on the value of another column in the table.
My problem being I need to check the values of the other column as they are retrieved, they will either be 1 or -1 and that value will set the design of the button.
How can I check the values of this bound field -
<asp:BoundField DataField="EXCLUDE" HeaderText="EXCLUDE" SortExpression="EXCLUDE"
ReadOnly="True" HeaderStyle-CssClass = "hideGridColumn"
ItemStyle-CssClass="hideGridColumn"/>
To then set the colour and text of the button?
You can use the RowDataBound event of the gridview, for example:
myGrid.RowDataBound += new GridViewRowEventHandler(myGrid_RowDataBound);
void myGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Raised after each row is databound
if (e.Row.RowType == DataControlRowType.DataRow)
{
string value = e.Row.Cells[5].Text; //sixth column
if (value == "1")
{
//change button color (assuming button is in first column)
Button myButton = e.Row.Cells[0].Controls[0] as Button;
myButton.BackColor = Color.Red;
Change it as follows
<ItemTemplate>
<asp:Button ID="statusButton" runat="server" Text="Select"
OnClick="statusButton_CheckedChanged" />
</ItemTemplate>
use different css-classes according to your condition
.class1{
color:red;
font-size:10;
}
.class2{
color:blue;
font-size:12;
}
<ItemTemplate>
<asp:Button ID="statusButton" runat="server" Text="Select"
CssClass='<%# Convert.ToString(Eval("EXCLUDE"))== "1" ? "class1" : "class2" %>'
OnClick="statusButton_CheckedChanged" />
</ItemTemplate>
You can use it from the C# on RowDataBound event as suggested by #edwin

Acces label in footertemplate of gridview in javascript

I have a label in a footertemplate of a gridviewcolumn. I want to put a calculated value (total of the rowvalues) in this label in javascript. I can access all the textboxes in my Itemtemplates, but I don't know how to find my label in my foortertemplates.
.aspx: column in gridview
<asp:TemplateField HeaderText="Prijs excl. BTW">
<ItemTemplate>
<asp:TextBox ID="txtBTWTarief" Width="60px" runat="server" Text='<%# Eval("exclBTW") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotexclBTW" runat="server" Text="0" Width="60px"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
.aspx.cs: eventhandlers attached to my textboxes and ddl
protected void gridviewDiversen_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string evtHandler;
int rowIndex = Convert.ToInt32(e.Row.DataItemIndex) + 1;
evtHandler = "updateValue(" + gridviewDiversen.ClientID + "," + rowIndex + ")";
((TextBox)e.Row.FindControl("txtBTWTarief")).Attributes.Add("onblur", evtHandler);
((TextBox)e.Row.FindControl("txtKorting")).Attributes.Add("onblur", evtHandler);
((DropDownList)e.Row.FindControl("ddlBTW")).Attributes.Add("onchange", evtHandler);
}
}
javascript: eventhandlers in action
function updateValue(theGrid, rowIdx)
{
var ddl, t1, t2, l1, l2, l3, l4, k1;
ddl = document.getElementById(theGrid.rows[rowIdx].cells[2].children[0].id);
t1 = document.getElementById(theGrid.rows[rowIdx].cells[3].children[0].id);
//calculations...
}
In this script I find my textboxes in the Itemtemplate, but I don't know how to find my labels in the footer template. Anyone an idea? Thx
If you do calculations in JS and need to find the label using client side you can use jQuery:
$('.yourLabelClass').html('Updated results');
or just JS:
var labels = document.getElementsByTagName("span");
for (var i=0; i < labels[i]; i++) {
if (labels[i].className && labels[i].className == 'yourLabelClass')
labels[i].innerHTML = 'Updated results';
}

Categories

Resources