Data binding along with the value in ASP.NET - asp.net

How do you achive something like below in asp.net?
<asp:Label runat="server" Text="The '<%# CustomValue %>' you assigned."/>

This usually depends on where your Label resides. If it is a stond alone control, not nested inside a repeater, you just set your code in code behind:
Label1.Text = $"The {CustomValue} you assigned.";
If the label is nested inside an ItemTemplate in some sort of Repeater control, you can strongly type it to an objects property:
<asp:Repeater runat="server" ID="MyRepeater" ItemType="WebFormsSandbox.Person">
<ItemTemplate>
<li>
<%#: Item.FirstName %> <%#: Item.LastName %>
</li>
</ItemTemplate>
</asp:Repeater>
and the corresponding code behind:
protected void Page_Load(object sender, EventArgs e)
{
MyRepeater.DataSource = Persons();
MyRepeater.DataBind();
}
IEnumerable<Person> Persons()
{
for (int i = 0; i < 10; i++)
{
yield return new Person { Id= i, FirstName = $"Foo{i}", LastName = $"Bar{i}" };
}
}
This would create a list of links, where you then could do anything with it. Whether this would pop up a custom window or does a postback .. up to you.

If you really want to do it that way, write the string inside the server tags.
<asp:Label runat="server" Text='<%# "The " + CustomValue + " you assigned." %>'/>
However if the Label is not inside a GridView, Repeater etc you have to call DataBind manually.
protected void Page_Load(object sender, EventArgs e)
{
DataBind();
}

You would typically do this in the code behind on page load, unless you were using a datagrid or repeater control. Assign an ID to your control and reference it like so.
<asp:Label runat="server" ID="Label1" />
protected void Page_Load(object sender,EventArgs e)
{
Label1.Text = "Your Value";
}

Related

Simultaneously deleting a file from a DataBase and a Folder using a LinkButton or Gridview_RowDeleting method

HELP! Is it achievable to use LinkButton or Gridview_RowDeleting method to simultaneously delete a file from a DataBase and from a Folder? Below is my code using a LinkButton:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID = "lnkDelete" Text = "Delete" OnClientClick="return confirm('Are you sure you want to delete this record?');" CommandArgument = '<%# DataBinder.Eval(Container.DataItem,"ID") %>' runat = "server" OnClick = "DeleteFile" />
</ItemTemplate>
</asp:TemplateField>
Code Behind:
protected void grdProducts_RowEditing(object sender, GridViewEditEventArgs e)
{
//Get seleted row
GridViewRow row = grdProducts.Rows[e.NewEditIndex];
//Get Id of selected product
int rowId = Convert.ToInt32(row.Cells[1].Text);
//Redirect user to Manage Products along with the selected rowId
Response.Redirect("~/Pages/Management/ManageProducts.aspx?id=" + rowId);
}
protected void DeleteFile(object sender, EventArgs e)
{
string filePath = (sender as LinkButton).CommandArgument;
File.Delete(filePath);
Response.Redirect(Request.Url.AbsoluteUri);
}
PL: I have an existing gridview and a datasource for my table.
Thank you all for your contribution. I later got the answer to this. I will like to share it with all. Just enable OnRowDeleting in your Gridview properties then use the code behind below.
protected void grdProducts_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Image oImg = grdProducts.Rows[e.RowIndex].FindControl("ImageFile") as Image;
if (oImg != null)
{
string sUrl = oImg.ImageUrl;
File.Delete(Server.MapPath(sUrl));
grdProducts.DataBind();
}
}
}
Finally: put this TemplateField on your aspx page.
<asp:TemplateField>
<ItemTemplate>
<asp:Image ID="ImageFile" runat="server" ImageUrl='<%# Bind("Image", "Images/Products/{0}")%>' AlternateText="Picture unavailable" style="width:50px; height:40px" />
</ItemTemplate>
</asp:TemplateField>

How to get Reference to the label in repeater item in code behind

<asp:repeater id="rpt" run="server">
<ItemTemplate>
<asp:LinkButton id="Delete" runat="server" OnCommand="Delete_Command"></asp:linkButton>
<asp:label id="lblMessage" run="server">
</ItemTemplate>
</asp:repeater>
Code Behind:
protected void Delete_Command(object sender, CommandEventArgument e)
{
}
how i get the reference to the "lblMessage" in Delete_Command.
Try this:
protected void Delete_Command(object sender, CommandEventArgs e)
{
LinkButton button = (LinkButton)sender;
Label label = (Label)button.NamingContainer.FindControl("lblMessage");
// do something with the label
}
If you:
Have bound the repeater
Have ViewState enabled
Do not re-bind the repeater earlier in the post back
this should work. If not, please verify that the id of the label is indeed exactly the same as in the ...FindControl("lblMessage");. Also make sure that runat="server" is set on all the controls involved.
Edit: One more thing to check: Search the markup file (the .aspx file) and check if there are any other controls that also use the same event in the code behind. If another control is using the same event handler and that control is not in the repeater, the label will not be found.
means are you want find a lable in Delete_Command event?
in aspx
<asp:Repeater ID="rpt" runat="server">
<ItemTemplate>
<asp:LinkButton ID="Delete" runat="server" OnCommand="Delete_Command"></asp:LinkButton>
<asp:Label ID="lblMessage" run="server">
</ItemTemplate>
</asp:Repeater>
in aspx.cs
protected void Delete_Command(object sender, CommandEventArgs e)
{
foreach (RepeaterItem item in rpt.Items)
{
Label lblMessage = item.FindControl("lblMessage") as Label;
if (lblMessage != null)
{
lblMessage.Text = "";
}
}
}
If You want to make it in your way use following code in
protected void Repeater1_ItemCommand(object source, CommandEventArgs e)
{
(((LinkButton)source).NamingContainer).FindControl("lblName")
}
Another approach.. But something that you can buy
aspx
<asp:Repeater ID="Repeater1" runat="server"
onitemcommand="Repeater1_ItemCommand">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%=Eval("Name") %>' ></asp:Label>
<asp:LinkButton runat="server" CommandName="Delete_Command" Text="sd"></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
.cs
protected void Delete_Command(object sender, CommandEventArgument e)
{
if(e.CommandName != null)// Conditional Check
{
Label label = e.Item.FindControl("lblMessage");
// do something with the label
}
}

ASP.NET - Finding Label Control in a GridView

I'm having a problem trying to find a label control that is inside a GridView.
Please see my codes below:
<asp:GridView ID="MyGridView" runat="server">
<Columns>
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtDate" MaxLength="10" Width="70" />
<asp:ImageButton ID="imgScoreDate" runat="server" ImageUrl="~/images/calendar.gif" />
<ajaxtoolkit:CalendarExtender ID="txtDate_CalendarExtender" runat="server" Enabled="True" Format="MM/dd/yyyy" TargetControlID="txtDate" PopupButtonID="imgDate" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And here is my .cs file:
protected void LoadGridView()
{
//Do something else
foreach (GridViewRow row in MyGridView.Rows)
{
//Tried A
System.Web.UI.WebControls.Label lblName = row.FindControl("lblName") as System.Web.UI.WebControls.Label;
lblName.Text = "Name";
//Tried B
((System.Web.UI.WebControls.Label)row.FindControl("lblName")).Text = "Name";
}
}
I debug this code and it seems to work fine because my breakpoint is being hit each time the debugger runs. It even loops through my foreach block the same count as to how many rows my GridView has.
But I don't understand why my lblName control doesn't get the "Name" text as a value? Am I missing anything here? I tried both //Tried A and //Tried B methods but they both doesn't update my label's text.
Any help would be appreciated!
Thanks! Cheers!
You want to call LoadGridView inside PreRender. Basically, you want to call it after GridView is bound with data.
protected void Page_PreRender(object sender, EventArgs e)
{
LoadGridView();
}
Look at PreRender event of ASP.NET Page Life Cycle.
On your gridview add:
<asp:GridView OnRowDataBound="MyGridView_RowDataBound" ... />
Then define MyGridView_RowDataBound:
void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
Label l = (Label) e.Row.FindControl("lblName");
}
What I think is happening is the control is not recreated server side in its current spot.
try this
on .aspx page
<asp:GridView ID="MyGridView" runat="server"
onrowdatabound="MyGridView_RowDataBound" .../>
code behind ::
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadGridView();
}
}
void LoadGridView()
{
DataTable dt = new DataTable();
// dt= call ur database method to get data
MyGridView.DataSource = dt;
MyGridView.DataBind();
}
protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl_Name = (Label)e.Row.FindControl("lblName");
lbl_Name.Text = "Name";
}
}
cheers!

Why is my repeater control empty on postback?

I think this is a "doh" moment caused by me not having dome WebForms dev for a few years..
I have a repeater which which contains a bunch of checkboxes:
<asp:Repeater EnableViewState="true" ID="IDTypesRepeater" runat="server" OnItemDataBound="IdTypesRepeaterItemDataBound">
<HeaderTemplate/>
<ItemTemplate>
<asp:CheckBox EnableViewState="true" ID="chkIdType" Text="<%# ((KeyValuePair<string,int>)Container.DataItem).Key %>" runat="server" />
<asp:HiddenField ID="idType" Value="<%# ((KeyValuePair<string,int>)Container.DataItem).Value %>" runat="server"/>
<br />
</ItemTemplate>
</asp:Repeater>
I need to get the checkboxes that are selected in the code behind:
foreach (RepeaterItem repeaterItem in IDTypesRepeater.Items)
{
if ( ((CheckBox)repeaterItem.FindControl("chkIdType")).Checked )
{
// Do something
}
}
But on postback, this code isn't working! I know about always databinding a repeater, so I've done this:
protected void Page_Load(object sender, EventArgs e)
{
IDTypesRepeater.DataSource = DocTemplateHelper.GetApplicableIDTypes().Where(type => type.Value != 0);
IDTypesRepeater.DataBind();
}
So this repopulates the repeater, but the Update code never finds any checked checkboxes.. Any ideas?
Bind in the Page_Init event
protected void Page_Init(object sender, EventArgs e)
{
IDTypesRepeater.DataSource = DocTemplateHelper.GetApplicableIDTypes().Where(type => type.Value != 0);
IDTypesRepeater.DataBind();
}
Be sure to use the !Page.IsPostBack method in your pageload.
Otherwise, the Repeater will keep getting reset, and all your checkboxes
will be in there default value (unchecked)
This should fix it. You are binding the control on postback hence losing the values. You can bind it after handling any event to show the updated record.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
IDTypesRepeater.DataSource = DocTemplateHelper.GetApplicableIDTypes().Where(type => type.Value != 0);
IDTypesRepeater.DataBind();
}
}

Handling the checkedchanged event of inner repeater Checkbox control in asp.net nested repeaters

I have nested repeaters on my aspx page.In the outer repeater I am displaying a list of products and in the inner repeater I am displaying a list of additional options associated with each product.The inner repeater contains a checkbox,textbox,label and other stuff.I would like to find the controls inside the outer repeater when a user selects a checkbox in the inner repeater.In order to handle this I am using the following code.
<asp:Repeater ID="OuterRepeater" runat="server"
onitemdatabound="OuterRepeater_ItemDataBound" >
<ItemTemplate>
<asp:Label ID="CodeLabel" runat="server" Text='<%# Eval("Code") %>'></asp:Label>
<asp:Repeater ID="InnerRepeater" runat="server" OnItemCreated="InnerRepeater_ItemCreated">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true"/>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
......
.......
</ItemTemplate>
</asp:Repeater>
......
......
</ItemTemplate>
</asp:Repeater>
protected void InnerRepeater_ItemCreated(object sender, RepeaterItemEventArgs e)
{
RepeaterItem ri = (RepeaterItem)e.Item;
if (ri.ItemType == ListItemType.Item || ri.ItemType == ListItemType.AlternatingItem
)
{
CheckBox cb = ri.FindControl("CheckBox1") as CheckBox;
cb.CheckedChanged += new EventHandler(CheckBox1_CheckedChanged);
}
}
private void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox cb = (CheckBox)sender;
if (cb.Checked)
{
//do something
}
else
{
//do something
}
}
But the checkedChanged event of the checkbox is not firing for some reason.Also I am not sure how to access the textbox of the outer repeater in the checked changed event of the innter repeater checkbox control.
Could someone please help me with this?
Thanks
It does not fire the CheckedChanged event, since you have declared the event handler as private, You have to make it Protected or Public
Protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
You can access the Textbox control like..
private void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox checkBox = (CheckBox)sender;
Textbox textbox1 = (TextBox)checkBox.Parent.FindControl("TextBox1");
String textboxText = textbox1.Text;
}
It doesn't look like you defined an event handler in your markup.
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true" OnCheckedChanged="CheckBox1_CheckedChanged" />
Muhammad Akhtar's answer helped me a lot today!
I just needed to set a specific ID to my dynamic generated checkboxes inside my reapeater to recover the origin of the event, and do the rest of the processing, and it worked perfectly.
chkAtivo.ID = DataBinder.Eval(e.Item.DataItem, "id").ToString();
Reovered just as the sample.
Cant vote up yet, but thank you.

Resources