find control inside datalist in button event - asp.net

I had data list as label for Question and textarea for Answer ,as
datalist render Question on label and the user will add the Answer in
text area as the answers inserted in database. I did my code , but
when I add my code to find the controls (label,textarea) they returned
with null value although I add answers for the Questions .
protected void BT_submit_Click(object sender, ImageClickEventArgs e)
{
Label QID = (Label)Dl_Question.FindControl("lbl_QID");
HtmlTextArea QAnswer = (HtmlTextArea)Dl_Question.FindControl("Txt_Answer");
}
DataList code:
<asp:DataList ID="Dl_Question" runat="server" onitemdatabound="Dl_Question_ItemDataBound" onitemcommand="Dl_Question_ItemCommand">
<ItemTemplate>
<asp:Label ID="lbl_QID" runat="server" Text='<%# Eval("ID") %>' Visible="false">
</asp:Label><br />
<asp:Label ID="Lbl_Question" runat="server" Text='<%# Eval("Question") %>'></asp:Label> <br />
<textarea id="Txt_Answer" cols="80" rows="5" runat="server"></textarea>
</ItemTemplate>
</asp:DataList>

I would assume you are looking at higher level than you think. You might need something like this:
Label QID = Dl_Question.**Items[n]**.FindControl("lbl_QID") as Label;

If you don't want to bother specifying the control heir achy use a recursive algorithm.

Related

How to get Text box value from Grid view header template?

I want grid view header template textbox value. I write code for getting value but it return null.
<asp:Button ID="btngetLocationDate" runat="server" Text="Get Filtered Data" OnClick="getTextBoxValue"></asp:Button>
<asp:TemplateField HeaderText="Mobile Number">
<HeaderTemplate>
Mobile Number:
<asp:TextBox ID="txtMobilenumber" runat="server" ></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblmobile" runat="server" Text='<%# Eval("Mobile Phone") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
And On the code behind.cs i write that code but it returns null
protected void getTextBoxValue(object sender, EventArgs e)
{
//TableCell cell1 = TrackerGrid.HeaderRow.Cells[0];
TextBox mobilenumber = (TrackerGrid.HeaderRow.FindControl("txtMobilenumber") as TextBox) ;
string mobile = mobilenumber.Text;
How can I resolve this ? please help me!
I've just had a similar problem by trying to get textbox text from the footer row. I'm not sure if this is the best way to get around this problem but this should work if FindControl() successfully assigns the textbox.
TextBox mobilenumber = (TrackerGrid.HeaderRow.FindControl("txtMobilenumber") as TextBox);
string mobile = Request.Form[mobilenumber.UniqueID];
EDIT: As VDWWD commented, Request.Form is a bad practice. But for my particular usage I couldn't find any other way to get the data from a textbox on button click due to my unorganized postbacks.

ASP.NET Repeater FindControl not working for Label, but works for Textbox

I'm facing issues trying to get controls from my repeater. I have one label and one textbox. The label is giving me a null reference error, however the textbox is working.
Markup:
<asp:Repeater ID="PalletsRepeater" runat="server" OnItemDataBound="PalletsRepeater_ItemDataBound">
<ItemTemplate>
<div style="margin-left: 20px; margin-top: 5px;">
<asp:Label lbl="lblPalletId" Text='<%#"Pallet "+Eval("PALLETID")%>' runat="server" />
<asp:Label Text=", Qty = " CssClass="field-label-blue" runat="server" />
<asp:TextBox ID="txtPalletItemQty" runat="server" Text='<%# Eval("ITEMQTY") %>' step="1" type="number" />
</div>
</ItemTemplate>
</asp:Repeater>
Code Behind:
foreach (RepeaterItem repeaterRow in PalletsRepeater.Items)
{
// This fails.
string palletId = ((System.Web.UI.WebControls.Label)repeaterRow.FindControl("lblPalletId")).Text;
// This works.
string palletItemQty = ((System.Web.UI.WebControls.TextBox)repeaterRow.FindControl("txtPalletItemQty")).Text;
}
I have researched this on Stack Overflow and most answers involve using the OnItemDatabound event, but when I tried to implement those answers, it still comes back null for the label. Personally I don't understand the suggestions as far as using the OnItemDatabound event.
Change
<asp:Label lbl="lblPalletId" Text='<%#"Pallet "+Eval("PALLETID")%>' runat="server" />
Into
<asp:Label id="lblPalletId" Text='<%#"Pallet "+Eval("PALLETID")%>' runat="server" />
You cannot find it because it has no ID

Update on GridView combobox not updating

I am trying to bind the DropDownList(DDL) with my entity datasource. The GridView(GV) is bound to a different EntityDataSource than the DDL. The GV's EntityDataSource has a navigation property 'Bag' for the relationship. In edit mode I can pick a different item, but it does not update the database for that record. I did use the include for the navigations in the EntityDataSource. I am sure the wiring is not correct. I have tried searching with no luck so far. Thanks for the help.
<asp:TemplateField HeaderText="Bag">
<ItemTemplate >
<asp:Label ID="lbEditBag" Text='<%#Eval("Bag.Item1") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate >
<asp:DropDownList runat="server" ID="ddlBags" DataSourceID="edsBags" DataTextField="Amount" DataValueField="BagId" />
</EditItemTemplate>
</asp:TemplateField>
DonA, if you've not found your answer yet I will explain what I have done to do something similar to what your after I believe.
In a gridview I have various asp:TempleteField's, one which is like this:-
<ItemTemplate>
<asp:Label ID="lblActive" runat="server" Text='<%# Bind("Active") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<%--<asp:TextBox ID="txtboxActive" runat="server" Text='<%# Bind("Active") %>' Width="20px" TextMode="SingleLine" CssClass="textboxEdit"></asp:TextBox>--%>
<asp:DropDownList ID="activeDDL" CausesValidation="False" AutoPostBack="False" runat="server"> <asp:ListItem Text="No" Value="0"></asp:ListItem>
<asp:ListItem Text="Yes" Value="1" Selected="True"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
which as you can see has two dropdownlist items in the EditItemTemplete (I also left in similar code to yours that I used to use to bind to a database for the DDL values but I don't use anymore so is commented out)
then alongside the ID, runat="server", DataKeyNames, etc. in
<asp:Gridview ID=""...
i have
OnRowUpdated="info_GridView_RowUpdated"
This then runs in my C# code behind an SQL function to update the database table with the setting from the DDL, like so (I have also put in a few other Gridview.Databind() to reset my other gridviews)
protected void info_GridView_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
// The update operation was successful. Retrieve the row being edited.
int index = info_GridView.EditIndex;
GridViewRow row = info_GridView.Rows[index];
int itemID = Convert.ToInt32(row.Cells[4].Text); // Cells[4] is only one available as others are being edited!
// update Active value in the database //
comm = new SqlCommand("UPDATE Products SET Active=#active WHERE ItemID=#itemID", objConn);
comm.Parameters.AddWithValue("#active", ddlValue); // this stores DDL value in database
comm.Parameters.AddWithValue("#itemID", itemID);// Convert.ToInt32(propertyRefTextBox.Text));
objConn.Open();
comm.ExecuteNonQuery();
objConn.Close();
// force update and reset selectedIndex of other gridviews //
Category_GridView.DataBind();
editImages_GridView.DataBind();
Category_GridView.SelectedIndex = -1;
editImages_GridView.SelectedIndex = -1;
}
hope the above helps.
Trev.

Customize label text in grid view template field

I want to show "N/A" text in grid view label if value is not available in database and if it is available, then the value should be displayed instead of "N/A".
How can I customize my label?
This is the code that I have written to get the value.
<asp:Label ID="lblCineRunFrom" runat="server" Text='<%# Eval("CineRunFrom") %>'></asp:Label>
This works:
<asp:Label id="dada" runat="server" Text='<%# string.Format("{0}",string.IsNullOrEmpty(Eval("CineRunFrom").ToString())?"N/A":Eval("CineRunFrom")) %>' ></asp:Label>
You may use this: Text='<%# Eval("CineRunFrom")?? "N/A" %>'
Add a new function in code behind & call it from HTML code, check sample code below.
Code
Private Function GetDisplayText(ByVal CineRunFrom As String) As String
'Do whatever you want here and return text to dispaly as required
End Function
HTML
<asp:Label ID="lblCineRunFrom" runat="server" Text='<%# GetDisplayText(Eval("CineRunFrom")) %>'></asp:Label>

ASP.NET GridView ItemTemplate

OK I have a GridView and there is a column that I want to be a link if a file exists, otherwise I just want it to be a label. Right now I am changing the controls on RowDataBound event handler using the Row passed in the args. I am not a big fan of this as I am hard coding the column ID, and if it ever changes I will need to remember to change this code. I was hoping I could do a conditional in the asp code to add a link if a property value is not null otherwise add a label. Is this possible? Any different solutions?
I would like something like this:
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<%# if (Eval("LogFileName") == null)
<%#{
<asp:LinkButton ID="LogFileLink" runat="server" CommandArgument='<% #Eval("LogFileName") %>' CommandName="DownloadLogFile" Text='<%# Blah.NDQA.Core.Utilities.GetEnumerationDescription(typeof(Blah.NDQA.Core.BatchStatus), Eval("Status")) %>'>
<%# }
<%# else
<%#{
<asp:Label ID="LogFileLabel" runat="server"Text='<%# Blah.NDQA.Core.Utilities.GetEnumerationDescription(typeof(Blah.NDQA.Core.BatchStatus), Eval("Status")) %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
You can continue to use RowDataBound event but in your aspx you add:
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
In your C# code something like that:
if (LogFileName) {
LinkButton ctrl = new LinkButton();
ctrl.CommandArgument= ...;
ctrl.CommandName= ...;
} else {
Label ctrl = new Label();
ctrl.Text= ...;
}
// You have to find the PlaceHolder1
PlaceHolder1.Controls.Add(ctrl);
In this way you don't have to hard coding the column ID
I know this is a little old now but just in case someone else stumbles across this as I did when looking for an answer to a similar question, I found you can do something like this:
<ItemTemplate>
<asp:ImageButton ID="btnDownload" runat="server"
CommandName="Download"
CommandArgument='<%# Eval("Document_ID") & "," & Eval("Document_Name") %>'
ImageUrl="download.png" ToolTip='<%#"Download " & Eval("Document_Name") %>'
Visible='<%# Not(Eval("Document_ID") = -1) %>' />
</ItemTemplate>
i.e. set the Visible property to evaluate a boolean expression based on your field. If you wanted to display something instead of the download link or button, such as a "Not available" label, then you would just set its Visible property to the opposite boolean expression to your download link. (This is VB.NET not C#, but you get the idea.)
If you're going to be doing this a lot, I suggest writing your own field. The simplest approach is probably to make a NullableHyperlinkField inheriting from HyperlinkField, and render out a plain string if the anchor's URL would otherwise be null.
Use properties on the page to determine if you want to show the label or the link
<asp:GridView ID="gv" runat="server">
<Columns>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:LinkButton runat="server" Visible='<%# ShowLink %>' PostBackUrl="~/Aliases.aspx" >This is the link</asp:LinkButton>
<asp:Label runat="server" Visible='<%# ShowLabel %>'>Aliases label</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The add the properties ShowLink and ShowLable toyour code behind
public bool ShowLabel
{
get
{
//determine if the label should be shown
return false;
}
private set
{
//do nothing
}
}
public bool ShowLink
{
get
{
//determine if the link should be shown
return true;
}
private set
{
//do nothing
}
}

Resources