find control in listview - asp.net

By pressing button in GridView i need to find control in Listview.
<ItemTemplate>
<td>
<asp:Label ID="lblMarketLVBalanceHeader" runat="server" Text="Balance: "></asp:Label>
</td>
<td>
<asp:Label ID="lblMarketLVBalanceValue" runat="server" Text='<%# Bind("Money", "{0:####}$") %>'></asp:Label>
</td>
</ItemTemplate>
Code Behind:
protected void GVMarketItems_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Buy"))
{ GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
/* string itemID = row.Cells[0].Text;
string itemName = row.Cells[1].Text;
string itemCostStr = row.Cells[3].Text; */
string curBalanceStr = ((Label)LVMarketBalanceShow.FindControl("lblMarketLVBalanceValue")).Text;
}
Code seems find, but i have "Object reference not set to an instance of an object" when i'm trying to Find control.
string curBalanceStr = ((Label)LVMarketBalanceShow.FindControl("lblMarketLVBalanceValue")).Text;
Did the same to DetailsView and it was Ok.. What's wrong with ListView?
UPD: Trying to get first fow of listview
ListViewDataItem curBalanceLV = LVMarketBalanceShow.Items[0];
string curBalanceStr =((Label)curBalanceLV.FindControl("lblMarketLVBalanceValue")).Text;
But getting an error "Index was out of range."

I think you want to find the control within the specific row.
string curBalanceStr = ((Label)row.FindControl("lblMarketLVBalanceValue")).Text

Did the same to DetailsView and it was Ok.. What's wrong with
ListView?
A DetailsView is used to tackle with one row at a time so you can directly call FindControl() on the detailsview but gridview and listview are meant to display multiple records and your markup you define inside <ItemTemplate /> is just a template for each row. You'll be able to find the controls that you define in the template inside of each row.

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 binding query output into dropdown list in gridview

this is for ticketing system where the tickets are in different status like 'open, rejected, closed, resolved..'
In asp.net i have a gridview and in the gridview there are textboxes and a dropdownlist.
i can get output from the database and get to populate it in the gridview and also the contents in the dropdown list are also displayed.
how can i get to bind the data of the dropdownlist in the grid to that of the output of the query. if the ticket is closed it should select closed, if the ticket is rejected it should select rejected.
in the onrowCommand, i fetch data from another table and populate into the dropdown list. this is the full list of status like 'oopen, rejected, closed, resolved..'
Your question is missing details like what markup you have used for gridview and also what code you have for RowDataBound event.
So, I have provided a sample answer that you can easily adapt to your situation.
I am assuming you have a gridview with an id of GridView1 that contains the following ItemTemplate ( other columns have been omitted since they are not needed to understand this approach).
You should have a hidden field in the template so you can store the current status of the row; also when you are binding your gridview you should be getting a column called Status for the row.
Sample Markup
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnRowDataBound="GridView1_OnRowDataBound">
<Columns>
<asp:TemplateField HeaderText = "Status">
<ItemTemplate>
<asp:HiddenField ID="hfStatus" runat="server" Value='<%# Eval("Status") %>' />
<asp:DropDownList ID="ddlStatus" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Then in your RowDataBound event where you are binding the dropdown for the row, you need to get the value of hidden field hfStatus and then set the selected item of dropdown using this value.
I have assumed that a method called GetStatusDropDownListData is there that gets the data for binding dropdown list.
Sample RowDataBound event
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlStatus = (e.Row.FindControl("ddlStatus") as DropDownList);
ddlStatus.DataSource = GetStatusDropDownListData();
ddlStatus.DataTextField = "Status";
ddlStatus.DataValueField = "Status";
ddlStatus.DataBind();
//Select the Status in DropDownList
string currentStatus = (e.Row.FindControl("hfStatus") as HiddenField).Value;
ddlStatus.Items.FindByValue(currentStatus).Selected = true;
}
}
i had used this code and its working now:
in asp file:
' Visible = "false" />
in the .cs file
string currentStatus = (e.Row.FindControl("lblStatus") as Label).Text;
ddlStatus.Items.FindByValue(currentStatus).Selected = true;

ASP.NET - How to get selectedvalues from dynamicallyproduced dropdownlists inside Repeater Control

Hi have the following vb code in ASP.NET:
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SQL_SRC_DEV_HIERACHY">
<ItemTemplate>
<p class="input_title">Hierachy:
<asp:Literal ID="Literal1" runat="server" Text='<%# Eval("Hierarchy_SKey")%>'></asp:Literal><br />
</p>
<asp:DropDownList ID="DropDownList_H" runat="server" DataSourceID="SQL_SRC_DEV_GROUPINGDESCS" DataTextField="Description" DataValueField="FTE_PARENT_SKEY"></asp:DropDownList><br />
</ItemTemplate>
</asp:Repeater>
I now need to get the selectedvalues for each instance of dropdown created, and += to a variable so that I can built a SQL INSERT command based on the selected values.
Can anybody point me in the right direction to achieve this please? Thanks.
You can loop the items in the Repeater in code behind and use FindControl to get the SelectedValue of the DropDownList.
protected void Button1_Click(object sender, EventArgs e)
{
//loop all the items in the repeater
foreach (RepeaterItem item in Repeater1.Items)
{
//use findcontrol to locate the dropdownlist and cast it back to one
DropDownList drp = item.FindControl("DropDownList_H") as DropDownList;
//display the result
Label1.Text += drp.SelectedValue;
}
}
Thanks VDWWD - I have converted to VB and it work perfectly! Much appreciated.
VB version shown below:
Protected Sub GEN_CODE()
Dim txtField As DropDownList
Dim DDL_Values As String = ""
For Each item In Repeater1.Items
//use findcontrol to locate the dropdownlist and cast it back to one
txtField = item.FindControl("DropDownList_H")
//display the result
DDL_Values += " " + txtField.SelectedValue
Next
End Sub

select data from gridview field and populate textbox

I'm trying to populate a single text box (or parameter) with data from a gridview column when I click on a button in that row.
Gridview gets it data from a sqlconnection
the gridview is
| Drawing |
| 12345 | VIEW
| 12346 | VIEW
the VIEW is a template button with an onclick event, when the user clicks the button the data from the Drawing column (12345) should be passed to ether a textbox or a paremeter. (this is the part I dont know how to do) once the Iv got the number in a textbox I can use it as pareameter and then a pdf is opened of that drawing, I have code for this and is working.
thanks for any help
If you are using C#, the simplest thing to do would be to add an in-built select command button to the gridview rows at runtime. Then on the selectedindexchanged event of the gridview simply access the cell of the selected row that you want the value from. You can then assign that string to anything you want. Like so:
protected void myGridView_SelectedIndexChanged(object sender, EventArgs e)
{
string myString = myGridView.SelectedRow.Cells[4].Text.ToString();
TextBox1.Text = myString;
}
Remember that the cell index collection is zero based, so [0] is actually the first cell in the row.
Use TemplateFields and the grid view's OnRowCommand event, like this:
Markup:
<asp:gridview id="GridView1"
OnRowCommand="GridView1_RowCommand"
runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBoxDrawing" runat="server"
Text="<%# Eval("Drawing")) %>" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="selc" runat="server" Text="View"
CommandName="View"
CommandArgument="<%# ((GridViewRow)Container).RowIndex %> />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-behind:
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked
if(e.CommandName == "View")
{
// Convert the row index stored in the CommandArgument
// property to an integer
var index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button clicked
// by the user from the Rows collection
var row = GridView1.Rows[index];
// Find the drawing value
var theDrawingTextBox = row.FindControl("TextBoxDrawing") as TextBox;
// Verify the text box exists before we try to use it
if(theDrawingTextBox != null)
{
var theDrawingValue = theDrawingTextBox.Text;
// Do something here with drawing value
}
}
}

Finding in which row a Button was clicked in a GridView/Repeater

I am binding a Repeater. Each row (is that the right word?) in the Repeater has a Button and a HiddenField. How do I determine the Value of the HiddenField based on which Button was clicked?
Code behind for Button's OnClick event:
protected void btnButton1_Click(object sender, EventArgs e)
{
Button btnButton1 = (Button)sender;
// how do i get this row's HiddenField Value?
}
edit: the CommandArgument suggestion from Pleun works but I am still having issues. I need to find the row(?) in the Repeater that the Button belongs to as there is also a TextBox in each row and I would need its value. So ideally I want to get that row and go FindControl("TextBox1") etc etc. Sorry, should have stated that in my initial question
What I like to do is add a CommandArgument to the button. In this code its an imagebutton but the idea is the same. So also no need for an extra hidden field.
<asp:ImageButton ID="btnMail" ImageUrl="~/imgnew/prof/sendlink.png"
CommandArgument='<%# Eval("id")%>'
And in the _Click event do
string id = ((ImageButton)sender).CommandArgument;
Update:
If you need all the data, you need a different event. The data in the repeater is available as Item in
RepeaterCommandEventArgs
in the Command event (RepeaterCommandEventArgs)
for handling the Command event see this example
http://www.asp.net/data-access/tutorials/custom-buttons-in-the-datalist-and-repeater-cs
or
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeatercommandeventargs.aspx
If you using Repeater you can identify elements in each row in the ItemDataBound.
If you using gridview use RowDataBound
Hope this helps
You can traverse upwards by getting the button's Parent, then doing a FindControl() on that control.
Row parentRow = (Row)((Button)sender).Parent;
var tBox = (System.Web.UI.WebControls.TextBox)parentRow.FindControl("myTextBox")
You may have to play around to see how deep the button is nested and with what control types to get to the appropriate parent.
My markup code:
<asp:Repeater ID="RptFiles" runat="server">
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>--</td>
<td><%#Eval("title")%></td>
<td>
<asp:FileUpload ID="fuVersion" runat="server" />
<asp:Button ID="btnUploadVersion" Text="Last opp" runat="server" OnClick="btnUploadVersion_Click" CommandArgument='<%#Eval("Id") %>' />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
My code behind
protected void Upload_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
var documentId = btn.CommandArgument;
//Get the Repeater Item reference
RepeaterItem item = btn.NamingContainer as RepeaterItem;
var fuVersion = (FileUpload)item.FindControl("fuVersion");
var filename = fuVersion.PostedFile.FileName
}

Resources