Getting the value of a Textbox in a TemplateField in a gridview - c#

i'm gonna keep it short and simple
I'm a software engineering student in the 12th grade and as my final project I have decided to make a website. What the website is about doesn't really matter. The problem is this:
In the picture attached there is a textbox inside a templatefield inside that gridview. I need to get the value that the user writes inside. After you write a value you press Purchase. I've looked at similar questions and none offered a working solution. What happens is the value just disappears. I find the right control with FindControl, but the value gets deleted somehow. How do I know I am at the right control? I went to the client side and added to the asp:TextBox the following:
Text="5"
This works perfectly, so I know it gets to the right control but something makes it disappear. My gridview is being populated by a DataSet that is two datasets combined, and I put the Merge command and the DataSource and DataBind are both in if (!this.IsPostBack). I am completely lost and have no idea what to do, Help is much appreciated.The Picture of the Gridview

All the controls in a GridView are accessible by searching the correct row with FindControl. For that you can send the row number as a CommandArgument and use that in code behind. So first start by using OnCommand instead on OnClick and set the CommandArgument on the aspx page.
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Purchase" OnCommand="Button1_Command" CommandArgument='<%# Container.DataItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
And then in code behind
protected void Button1_Command(object sender, CommandEventArgs e)
{
//get the rownumber from the command argument
int rowIndex = Convert.ToInt32(e.CommandArgument);
//find the textbox in the corrext row with findcontrol
TextBox tb = GridView1.Rows[rowIndex].FindControl("TextBox1") as TextBox;
//get the value from the textbox
try
{
int numberOfTickets = Convert.ToInt32(tb.Text);
}
catch
{
//textbox is empty or not a number
}
}

Related

Value of HiddenField Duplicated when called from Nested Gridvew Row Editing

Problem: I'm trying to get a value from a HiddenField object and set it to a string. A value of "foo" is being returned as "foo, foo".
Details:
I have a Nested Gridview, and I'm trying to make the child Gridview editable. I have a method GetChildQuery(string id) which form the sql query to get the data for the Child Gridview, and I have the id bound to a HiddenField object in the HTML as so:
<asp:Gridview ID="gvChild" runat="server" AutoGenerateColumns="false" OnRowEditing = "gvChild_RowEditing">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label runat="server" ID="lblNameChild" Text='<% Eval("Name")%>'></asp:Label>
<asp:HiddenField runat="server" ID="hidIDChild" Value ='<%# Bind("ItemID") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:Label runat="server" ID="lblNameChildEdit" Text='<% Eval("Name")%>'></asp:Label>
<asp:HiddenField runat="server" ID="hidIDChildEdit" Value ='<%# Bind("ItemID") %>' />
</EditItemTemplate>
</asp:TemplateField>
and I try to access it in the OnRowEditing method like:
protected void gvhild_RowEditing(object sender, GridViewEditEventArgs e) {
Gridview child = sender as Gridview;
string itemID = (child.Rows[e.NewEditIndex].FindControl("hidIDChild") as HiddenField).Value.ToString();
string sql = GetChildQuery(itemID);
child.EditIndex = e.NewEditIndex;
child.DataSource = GetData(sql);
child.DataBind();
}
The id is used in the WHERE clause of my SQL query, and therefore the output is incorrect if the value of the id is incorrect. I don't know I this problem is occurring because of how I bind data to the HiddenField or how I'm calling it from the RowEditing method, or something I'm completely overlooking.
Ref: To make the Nested Gridview, I mainly followed https://www.aspsnippets.com/Articles/Nested-GridView-Example-in-ASPNet-using-C-and-VBNet.aspx and https://www.aspforums.net/Threads/133072/Edit-Update-Delete-in-Nested-Child-GridView-in-ASPNet/ which has the general format for my GetData method as well.
EDIT: Problem subverted by replacing the string itemID instantiation to
string itemID= ((child.Rows[e.NewEditIndex].FindControl("hidIDChild") as HiddenField).Value.Split(','))[0].ToString();
essentially splitting the duplication, accessing the first element, converting that to a string, and setting that equal to y string itemID.
However while this subverts the problem, I would still appreciate anyone's feedback as to why the problem is occurring in the first place. Thanks!
You should look at your rendered html.
When dealing with one gridview there is only ever one row open for editing at a time. And within a row's TemplateField the ItemTemplate and EditTemplate are mutually exclusive, that is to say that, when rendered, you will see only one or the other.
Likewise in the code behind, you will only have access to either the ItemTemplate row or the EditTemplate row depending on which event you process on postback.
The same rules apply to a nested/child Gridview.
So for the case you describe, I assume you are trying to use some ID from the parent to build a query to populate the child. If so I do not believe you need any hidden fields at all. This ID fieldname from the parents query should be set in the DataKeyNames property of the parent gridview.
You should then be able to pass the value to the procedure you are building for the child as
protected void gvhild_RowEditing(object sender, GridViewEditEventArgs e) {
string sql = GetChildQuery(gvParent.SelectedDataKey.Value);
child.DataSource = GetData(sql);
child.DataBind();
// Given that you have just populated the child I do not think the
// following is accurate, but that's for you to decide
child.SetEditRow(e.NewEditIndex);
}
Hope this helps.

GridView Button reference on rowdatabound

I feel like I'm missing something obvious here but I'm just not getting it. I have a gridview with a template field column where i have a button and a hidden field. I'm trying to get the reference to both the button and the hidden field on row databound, as both the button's label and commandargument etc change depending on the other row data.
If i place a breakpoint in the area indicated in the code below, I can see that the hidden field is being assigned to properly, but the button is not. What am I missing here?
GridView.aspx
<asp:GridView ID="gvCurrentQueueStatus" runat="server" AutoGenerateColumns="False"
OnRowDataBound="gvCurrentQueueStatus_RowDataBound">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderText="Service Controls">
<ItemTemplate>
<asp:Button ID="btnSubmitCommand" runat="server" Text="Control" OnClick="btnSubmitCommand_Click" />
<asp:HiddenField ID="hdnQueueNumber" runat="server" Value='<%# Eval("ReportQueueNumber") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
GridView.aspx.cs
protected void gvCurrentQueueStatus_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button controlButton = (Button)e.Row.FindControl("btnSubmitCommand"); // FindControl fails
HiddenField hdnQueueNumber = (HiddenField)e.Row.FindControl("hdnQueueNumber"); // FindControl succeeds
// Other stuff
} // breakpoint here, successfully finds htnQueueNumber, but not btnSubmitCommand
}
Try this:
Button controlButton = e.Row.FindControl("btnSubmitCommand") as Button ;
Or try this way:
foreach (GridViewRow row in gvCurrentQueueStatus.Rows) {
Button controlButton = (Button)gvCurrentQueueStatus.Rows[row.RowIndex].FindControl("btnSubmitCommand");
}
So apparently my button was in fact getting properly assigned to, it was just not reporting as such when mousing over the variable in my debugger.
I'm not actually crazy, Visual Studio's debugger is however and needed the old "have you tried turning it off and on again".
Sorry about that those that helped look into my issue :3

Bind a textbox value in a label box using c# inside a uframe

I have entered a value in text box and click the button the value should bind in a label.
The code must be in c# not in query. There is no database also.how please say the code behind in c#. It is button click event. while click the button the page should post back and bind the data how to bind a textbox value in a label box using c#. The value must bind in postback method.
easy , take a look at the below code:
<asp:TextBox Id="txt1" runat="server" />
<asp:button Id="btn1" runat="server" onClick="Button1_Click"/>
<asp:Label Id="lbl1" runat="server"/>
//in the code behind implement the Button1_Click
protected void Button1_Click (object sender, EventArgs e)
{
lbl1.Text= txt1.Text;
}
It as easy as the following:
LabelID.Text = TextBoxID.Text;
Where LabelID is the ID of your Label control and TextBoxID is the ID of your TextBox control.
You should place this code inside the button click's event.
Update
Please use for your purpose ASP.NET Web Server Controls.
<asp:TextBox ID="textBoxId" runat="server"/>
<asp:Label ID="labelId" runat="server"/>
Then you can access the values of Text property of both the above controls, like above:
labelId.Text = textBoxId.Text;

Session Variable in ASP.NET returns previous value in ModalBox?

I have a question regarding passing Session Variables to a text-box in an Update Panel (which is displayed in a Modal PopUp).
This is the code I have so far:
ASPX CODE:
<asp:TemplateField HeaderText="Link">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" Text="Link" runat="server" OnClick="LinkButton1_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" OnLoad="panel_Load">
<ContentTemplate>
<asp:Button ID="OKButton" runat="server" Text="Close" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:ModalPopupExtender ID="mpe" runat="server" TargetControlID="ClientButton" PopupControlID="UpdatePanel1" OkControlID="OKButton">
</asp:ModalPopupExtender>
<asp:Button ID="ClientButton" runat="server" Text="Launch Modal Popup (Client)" style="display:none;" />
CODE BEHIND (C#):
protected void LinkButton1_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label lbl_nme = (Label)clickedRow.FindControl("lbl_name");
String string_nme = lbl_nme.Text.ToString();
Session["Name"] = string_nme;
mpe.Show();
}
protected void panel_Load(object sender, EventArgs e)
{
Label1.Text = (string)(Session["Name"]);
}
So basically I have a GridView with name, address etc… When the user clicks on a link in a row, then the value for the name field of that row is saved as a session variable. Then a Modal PopUp is displayed. The Modal PopUp should then show the Name which was saved as a Session variable.
The code sort of works. What I’m experiencing is that when I click a row, the Label1.Text in the Modal PopUp is empty. So if I close the PopUp then click another link in another row, the PopUp then displays the Name of the row that was clicked previously.
In other words.. If row 1 has Name “Kevin” and row 2 has Name “Nathaniel”, and I click a link to open the Modal PopUp of row 1, I would expect the PopUp to display “Kevin”. But it doesn’t. The first time I click a link after rebuilding the application, nothing is displayed. But say I click row 2 after clicking row1, then the Modal PopUp displays the value of the row I clicked before, i.e. “Kevin” when I expect it to be “Nathaniel”.
I hope I didn’t confuse anyone. I’m a newbie and I’m just getting into this stuff, so I’d appreciate it if someone could help me out, preferably with examples of code etc.
Thank you. Much appreciated.
The "Load" event (panel_Load) occurs before the "Click" event (LinkButton1_Click) so it only sees the previous value.
The quick fix is to set the label in the "Click" event as well. Unless ViewState is enabled for the label (ick!) the label may have to be [re]set in the "Load" as well, depending upon when/how updates occur.
See ASP.NET Page Life Cycle Overview and ASP.NET Application and Page Life Cycle: Page Events.
Happy coding.

Access Textbox inside DetailsView

Does anyone have any idea how I can set the text of a textbox inside a DetailsView field (c#)?
I've tried a few variations but all return out of context and object reference not set errors.
Heres my code...
ASPX:
<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px">
<Fields>
<asp:TemplateField HeaderText="Header Text">
<InsertItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text="test"></asp:TextBox>
</InsertItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
CS:
TextBox txt = (TextBox)DetailsView1.FindControl("TextBox1");
txt.Text = "Text ";
Cheers
That error likely means that there is nothing in your DetailsView yet. I bet if you put this in your code:
TextBox txt = (TextBox)DetailsView1.FindControl("TextBox1");
if (txt != null)
{
txt.Text = "Text ";
}
You'll see that txt is, in fact, null - this is because the FindControl method didn't find anything named "TextBox1" in the DetailsView.
You need to move this code to a point where you know the DetailsView has been populated (if it's bound to a DataSource, you could do this in the DataBound event of your DetailsView).
Also, I noticed that your TextBox is in an InsertItemTemplate. You won't find that TextBox1 until you put the DetailsView in edit mode, either by default:
<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px"
DefaultMode="Insert">
Or in code behind:
DetailsView1.ChangeMode(DetailsViewMode.Insert);
TextBox txt = (TextBox)DetailsView1.FindControl("TextBox1");
txt.Text = "Text ";
Hopefully that helps.
#jadarnel27 thank you for your information about putting the code in DataBound event. I had similar issue where a textbox value would only pass to DetailsView field (DefaultMode=Insert) with a button click event. I didn't want/need a button.
My scenario: code identifies if detailsview is needed (for insert). If record does not exist based on person selected from dropdown control, their PersonID is preloaded into the Person field of detailsview.
Using FindControl didn't work but using the following code did WHEN put in DataBound control.
// Get person selected from dropdown control and pass to DetailsView first row/cell
txtPerson.Text = Convert.ToString(ddlPersonSelect.SelectedValue);
TextBox tb = (TextBox)DetailsView1.Rows[0].Cells[1].Controls[0];
if (tb != null)
{
tb.Text = txtPerson.Text;
}
I hope this helps another newbie like me.

Categories