Cant get value from textbox on gridview - asp.net

I have a GridView on an ASP.NET page with a TemplateField column that has a TextBox in the ItemTemplate. I then have a command field which is supposed to pull the text from this TextBox and use it in a SqlCommand running a stored procedure.
Here is my C# code:
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = this.gvwSNConfirm.Rows[index];
TableCell intID = selectedRow.Cells[1];
int reqID = int.Parse(intID.Text);
// Get the SN from the text box on the selected row
TableCell snCell = selectedRow.Cells[0];
TextBox tbox = (TextBox)staffNum.FindControl("txtSN");
string stSN = tbox.Text.ToString();
When I add a break point to see the values for intID and tbox.Text I get the right ID but the Text for tbox is "".
The mark-up for the two columns I am referencing is
<asp:TemplateField HeaderText="SN">
<ItemTemplate>
<asp:TextBox ID="txtSN" runat="server" MaxLength="20" Width="100px" />
</ItemTemplate>
<HeaderStyle BackColor="#171695" Font-Names="Arial" Font-Size="Small" ForeColor="White" Wrap="true" />
</asp:TemplateField>
<asp:BoundField DataField="Request" HeaderText="Request" ReadOnly="true" SortExpression="Request" />
Can anyone provide any help why I cant get the text from the text box? It worked the first time round but subsequently all tbox text values have been "".
Many Thanks
Andy
NEW CODE (05/03/2010):
protected void gvwSecond_RowCommand(object sender, GridViewCommandEventArgs e)
{
if ((e.CommandName == "Confirm") || (e.CommandName == "Decline"))
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gvwSecond.Rows[index];
int secondID = int.Parse(row.Cells[1].Text);
TextBox txtsn = ((TextBox)row.FindControl("txtSecSN"));
string sn = txtsn.Text;

What event is this code in? You should e.Item.FindControl. If you are getting the right control for sure, but Text is empty, that means it's either not getting posted back, or it's being cleared somewhere else.

I had the same problem once. I also had to retrieve the text value from a TextBox in a GridView on server and I was always getting an empty string. I had to set EnableViewState="false" for both the Gridview and the Textbox and it worked like a charm.

Related

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;

Extract a BoundField to a Label

I have a DetailsView which works fine using a data access layer and a query string. However, I'd like to extract one of the fields and use it as the text in a label to go above the DetailsView as a title to that page.
Is this possible? And if so, how?
This is an abstract of the DetailsView:
<Fields>
<asp:BoundField DataField="bandname" HeaderText="Band" />
<asp:BoundField DataField="contactname" HeaderText="Contact" />
<asp:BoundField DataField="county" HeaderText="County" />
</Fields>
and the code behind:
if (Request.QueryString.Count != 0)
{
int id = int.Parse(Request.QueryString["bandid"]);
dtvBand.Visible = true;
List<Band> bandDetails = new List<Band> { BandDAL.AnonGetAllBandDetails(id) };
dtvBand.DataSource = bandDetails;
dtvBand.DataBind();
}
What I'd like to do is take the data in the first BoundField row and make it the text of a label. Pseudocode:
Label1.Text = (<asp:BoundField DataField="band")
I would not try to find the text on the DetailsView but in it's DataSource. You could use the DataBound event which is triggered after the DetailsView was databound, so it's ensured that the DataItem exists.
It depends on the Datasource of your DetailsView. Often it is a DataRowView. You have to cast it, then you can access it's column:
protected void DetailsView1_DataBound(Object sender, EventArgs e)
{
DetailsView dv = (DetailsView)sender;
string yourText = (string)((DataRowView)dv.DataItem)["ColumnName"];
Label1.Text = yourText;
}
If it's not a DataRowView use the debugger to see what dv.DataItem actually is.
I managed to achieve what I wanted using:
string titletext = dtvBand.Rows[0].Cells[1].Text.ToString();
dtvBand.Rows[0].Visible = false;
lblBand.Text = titletext;
It takes the first row of the DetailsView, puts it above the rest in a Label so it can be formatted as a header, then hides the first row of the DetailsView.
How about using a TemplateField as what Tim mentioned:
<Fields>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Band") %>' />
</ItemTemplate>
</asp:TemplateField>
</Fields>

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
}
}
}

ASP.Net, Datagrid: render column differently based upon value?

I've looked and looked and I'm not seeing the answer to this.
I have a datetime value that's getting bound to a datagrid. I want to display the column as either the datetime, or if said datetime is null, an asp:button for the users to click.
I can't seem to find specific information on how to do it. My initial approach was <% if blah blah then %>, but I can't seem to get at the dataitem in that manner. I've also looked at events, but nothing is jumping out at me as being the solution (I'm sure I'm wrong, I'm just not seeing it).
Any suggestions?
Assuming that you actually mean GridView instead of DataGrid, otherwise it would work similarly(ItemDataBound etc.).
You could use a TemplateField with a Label and a Button and switch visibility of both controls in RowDataBound:
protected void Grid_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var row = ((DataRowView)e.Row.DataItem).Row;
DateTime? date = row.Field<DateTime?>("DateColumn");
var lblDate = (Label)e.Row.FindControl("LblDate");
var btnDate = (Button)e.Row.FindControl("BtnDate");
lblDate.Visible = date.HasValue;
btnDate.Visible = !date.HasValue;
if (date.HasValue) lblDate.Text = date.ToString();
}
}
aspx:
<asp:GridView ID="GridView1" AutoGenerateColumns="false" OnRowDataBound="Grid_RowDataBound" runat="server">
<Columns>
<asp:TemplateField HeaderText="DateColumn">
<ItemTemplate>
<asp:Label ID="LblDate" runat="server"></asp:Label>
<asp:Button ID="BtnDate" Text="click me" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You should use Gridview if you are using ASP.NET 3.5 or higher. Using a templatefield column, add a button and label. In the rowdatabound event, you should show only the button or the label, using the Visible property, depending on whether there's a date or not.

find control in listview

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.

Resources