Get the text of a label in a listview - c#

I have a listview control which is populated with data from a database. I have used the label to display that data. Now I need to use the value of that label in some other place. I am trying to access the text value of the label control but it says
Object reference not set to an instance of an object.
But I do have value in the label.
<asp:ListView ID="msg_list" runat="server">
<ItemTemplate>
<table>
<tr class="myitem">
<td>
<asp:Label ID="reg_id_reply" runat="server" Text="helo" Visible="false" />
<asp:Label role="menuitem" ID="msg_lbl" runat="server" text='<%#Eval("msg")%>' /><i style=" color:Gray; " > from
<asp:Label ID="tme" runat="server" Text='<%#Eval("name")%>' />
<i> on </i>
<asp:Label ID="tmelbl" runat="server" Text='<%#Eval("tme")%>'/>
<a id="msg-reply" class="btn button" data-toggle="modal" data-target="#msg-rply" style="cursor:pointer;" ><i class="glyphicon glyphicon-share-alt white"> </i></a> </td>
<hr style=" margin-top:1px; margin-bottom:1px; " />
</tr>
</table>
<%--<hr style=" margin-top:1px; margin-bottom:1px; " />--%>
</ItemTemplate>
</asp:ListView>
This is how i tried to access the text of the label.Note that the code below is inside a button click event onClick of buttom.
Label mylbl = (Label)msg_list.FindControl("reg_id_reply");
string rid = mylbl.Text;

According to the description for Control.FindControl Method (String):
This method will find a control only if the control is directly contained by the specified container.
The direct container that your label is contained within is the ItemTemplate. Therefore you may need to build a recursive search for your label if you are starting with the listview. You could try the following code that is suggested from this MSDN page:
private Control FindControlRecursive(Control rootControl, string controlID)
{
if (rootControl.ID == controlID) return rootControl;
foreach (Control controlToSearch in rootControl.Controls)
{
Control controlToReturn = FindControlRecursive(controlToSearch, controlID);
if (controlToReturn != null) return controlToReturn;
}
return null;
}
However also note that the listview may change the id values of components in the item template. If you know the item index you want then you can use the method suggested in this post:
var theLabel = this.ChatListView.Items[<item_index>].FindControl("reg_id_reply") as Label;

Related

BackColor in codebehind only changing color directly around text

So I have a list view with a C# code behind. I'm attempting to set the background of the cell if the value of JobsCovered is > 1000 (for example) in my code behind. But instead of setting the background color of the entire cell, it only sets the background immediately around the text only. I have to be missing something very simple.
HTML:
<ItemTemplate>
<td runat="server" style="background-color:black;color: white;text-align:center;">
<asp:Label ID="PartDescriptionLabel" runat="server" Text='<%# Eval("PartDescription") %>' />
<br />
<asp:Label ID="PartNumberLabel" runat="server" Text='<%# Eval("PartNumber") %>' />
<br />
<div id="JobsCoveredBox" style="height:60px; line-height:60px">
<asp:Label ID="JobsCoveredLabel" runat="server" Text='<%# Eval("JobsCovered") %>' />
</div>
</td>
</ItemTemplate>
Code Behind:
protected void RepackOSR_ItemDataBound(object sender, ListViewItemEventArgs e)
{
// Retrieve the current item.
ListViewItem item = e.Item;
Label JobsCoveredLabel;
// Verify if the item is a data item.
if (item.ItemType == ListViewItemType.DataItem)
{
JobsCoveredLabel = (Label)e.Item.FindControl("JobsCoveredLabel");
System.Data.DataRowView rowView = e.Item.DataItem as System.Data.DataRowView;
//Store the value of "JobsCovered" from data source
Int32 currentJobCovered = Convert.ToInt32(rowView["JobsCovered"].ToString());
if (currentJobCovered > 1000)
{
//Why won't this change the entire background of the cell?
JobsCoveredLabel.BackColor = Color.Green;
}
}
}
It only does this...
Not the entire background
You want of course to color the div background I assume?
thus you need to tag the div as server control.
So, try this:
<div id="JobsCoveredBox" runat="server" style="height:60px; line-height:60px">
So, now we can grab/get the div say like this in your row data bind event
HtmlGenericControl mydiv = (HtmlGenericControl)e.Item.FindControl("JobsCoveredBox");
mydiv.Style.Add("background-color", "aliceblue");

Access Label control inside the detailsview control

I am trying to set the text of the label control which is inside detailsview but it's not working. But it's showing error "Object reference not set to an instance of an object."
can anyone guide me please.. ??
My front end code is:
<asp:Panel ID="sub_question_panel" runat="server">
<asp:DetailsView ID="DetailsView1" runat="server" CellPadding="6" ForeColor="#333333" AutoGenerateRows="false" GridLines="None" >
<Fields>
<asp:TemplateField>
<ItemTemplate>
<table id="Question_view_table">
<tr>
<td style="font-family:Arial Rounded MT;">
<label id="Question_no"><span style="font-size:20px;">Question</span>:</label>
<asp:Label ID="Ques_id_label" runat="server" Text="Label"></asp:Label></td>
</tr>
<tr>
<td style="height:20px"></td>
</tr>
<tr>
<td style="font-family:'Times New Roman'; font-size:18px; ">
<label id="Question_detail"><%# Eval ("Question") %></label>
</td>
</tr>
<tr>
<td style="font-family:'Times New Roman'; font-size:18px;">
<ol style="list-style:upper-alpha">
<li>
<label id="optn1"> &nbsp&nbsp<%# Eval ("Option1") %></label></li>
<li>
<label id="optn2"> &nbsp&nbsp<%# Eval ("Option2") %></label></li>
<li>
<label id="optn3"> &nbsp&nbsp<%# Eval ("Option3") %></label></li>
<li>
<label id="optn4"> &nbsp&nbsp<%# Eval ("Option4") %></label></li>
</ol>
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
</asp:Panel>
My back end code is:
protected void Page_Load(object sender, EventArgs e)
{
int question_id = 1;
Label Question_Id = DetailsView1.FindControl("Ques_id_label") as Label;
Question_Id .Text = Convert.ToString(question_id);
}
You must use the FindControl for a row, not DataListView
You want to find your label by id, But which one? For each row you have a label with id 'Ques_id_label' . So to find a specific label you must specify the intended row. I did not work with DataLisView but I know that it is logically similar to Asp:Repeater . To find a control in a row of a Repeater when a command is sent from a row:
protected void SaveAnswer(Object Sender, RepeaterCommandEventArgs e)
{
Label Ques_id_label = (Label)e.Item.FindControl("Ques_id_label");
Which with e.item you specify the intended row.
You use FindControl to find Ques_id_label, but then reference it normally anyway: Ques_id_label.Text =
It should be Question_Id.Text = Convert.ToString(question_id);, with the ID you assigned with FindControl.
But did it even compile? Do you use an editor like Visual Studio? Because when I tried your snippet it gave the error The name 'Ques_id_label' does not exist in the current context, as it is supposed to.

Change Css class on a Panel thats located inside a Asp:repeater

Hello and thanks for taking your time to read this.
I'm trying to change the CSS class of a panel thats located inside a Repeater when I select a RadioButton.
<div>
<asp:RadioButtonList OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged" AutoPostBack="true" ID="RadioButtonList1" RepeatDirection="Horizontal" runat="server">
<asp:ListItem Selected="True">Show Gallery</asp:ListItem>
<asp:ListItem>Show List</asp:ListItem>
</asp:RadioButtonList>
</div>
<div class="RpOutterFrame" runat="server" id="RpOutterFrame">
<asp:Repeater runat="server" ID="RP">
<ItemTemplate>
<panel class="ShowDiv" runat="server" id="RpInnerFrame">
<img runat="server" style="width: 80px;" id="ModelImg" class="ModelImg" src='<%# string.Format("~/Content/Img/ModelImg/{0}", Eval("Image")) %>' />
<br />
<%# Eval("Model") %>
</panel>
</ItemTemplate>
</asp:Repeater>
</div>
My C#:
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (RadioButtonList1.Items[0].Selected == true)
{
RpOutterFrame.Attributes["class"] = "RpOutterFrame";
Panel panel = (Panel)this.FindControl("RpInnerFrame");
panel.CssClass = "ShowDiv2";
}
}
As you can see the Panel already has the class ShowDiv and then I would like it to change the class to ShowDiv2 when I select/click the Radiobutton.
Anyone who can help me figuar what I'm doing wrong or fix the code?
A Repeater's purpose is to repeat something. So normally it contains multiple elements. Therefore the RepeaterItem is the NamingContainer which must contain unqiue ID's and where you can find your controls via FindControl(ID).
So this does not work since this is the Page which is not the NamingContainer of the Panel:
Panel panel = (Panel)this.FindControl("RpInnerFrame");
panel.CssClass = "ShowDiv2";
You have to loop all items:
foreach(RepeaterItem item in RP.Items)
{
Panel panel = (Panel)item.FindControl("RpInnerFrame");
panel.CssClass = "ShowDiv2";
}
Apart from that you should use the ASP:Panel instead of Panel.
So change
<panel class="ShowDiv" runat="server" id="RpInnerFrame">
// ...
</panel>
to
<ASP:Panel CssClass="ShowDiv" runat="server" id="RpInnerFrame">
// ...
</ASP:Panel>

NavigateUrl on Repeater ASP.net

I have a table in DB:
NOTICE(NUM,TITLE,CONTENT)
I use Repeater Control in ASP to show all the notices in DB, like:
+----------+------------+|
|title1 (readmore)|
|
|title2 (readmore)|
|
|title3 (readmore)|
......
+------------------------+
All I want is: I read a "title" then I clicked on (readmore), the new page will be opened ( show detail's notice) with the "content" of that notice. How can I assign the num of notice without display it to define the notice in next page?
I just assign the title to property Text of a Label ID="TITLE" because I want to show the title of each notice.
All information I want to show in the this page is: title and the readmore( link to the next page). So that I don't know how to assign the num
My asp page: notice.asp
<asp:Repeater ID="RepDetails" runat="server" >
<HeaderTemplate>
<table style=" width:565px" cellpadding="0" class="borber">
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Label ID="Title" runat="server" Text='<%#Eval("TITLE") %>' />
</td>
<td>
<asp:HyperLink ID="HyperLink1" runat="server" > (readmord)</asp:HyperLink>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
My C# code:notice.asp.cs
private void BindRepeaterData()
{
string sql = "select num,title from NOTICE";
DataTable ds = l.EXECUTEQUERYSQL(sql);
RepDetails.DataSource = ds;
RepDetails.DataBind();
}
And the next page: detailnotice.asp.cs
private void GetNotice()
{
string sql = "select * from NOTICE where num=" ;// num= the num of notice I choose in notice.asp page.
}
How can I assign a num in Label without display it? What property of Label Control or I should use a other Control ?
Hope you understand what I say. If you don't, please ask?
Basically the same as Sain but using the NavigateURL
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("NUM","~/detailpage.aspx?id={0}") %>' > (readmord)</asp:HyperLink>
hi you can ues anchor tag in place of hyper link button. you can pass num in the query string to the detail page.
<a href='detailpage.aspx?id=<%#Eval("NUM") %>'> (readmord)</a>
On details page you can get query string value and fetch details from database.
int myKey = 0;
if (!string.IsNullOrEmpty(Request.QueryString["id"]))
{
myKey = int.Parse(Request.QueryString["id"]);
// Use myKey to retrieve record from database
}

repeater databinding , with manipulation of certain data on every item binded

in a repeater, i want to do a function on every item bounded, example
<asp:Repeater runat="server" ID="rptArticleContent"
OnItemDataBound="rptArticleContent_ItemDataBound">
<ItemTemplate>
<tr>
<td width="365" valign="top" align="left" class="bodyContent" bgcolor="#FFFFFF">
<div>
<h2 class="h2">
<asp:Label runat="server" ID="dsds"> <%#Eval("Title") %></asp:Label>
</h2>
<div class="article-body">
<div class="Article-image">
<%#Eval("Image") %>
</div>
<%#Eval("Description") %>
</div>
<asp:Literal runat="server" ID="litArticleSource" Text='<%#Eval("Source") %>'>
</asp:Literal>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
in code behind i want to do some manipulation on the data inside the Literal
protected void rptArticleContent_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Literal litArticleSource = rptArticleContent.FindControl
("litArticleSource") as Literal;
string ArticleSourcesR = litArticleSource.Text;
}
ArticleSourcesR still gives null, somes told me that when catching the controle with rptArticleContent.FindControl i should add something so it would be applied on every item bounded, what is that missing clue.?? what should be added?
You don't want to use rptArticleContent in the function, rather e.Item which will return the current repeater item instance.

Categories

Resources