Set textbox visibility based on dropdownlist value in gridview - asp.net

I have a gridview that i would like to show or hide a text box based on the selected value of a dropdownlist on the same row.
My gridview:
<asp:GridView ID="GridViewUsers" runat="server" AutoGenerateColumns="False" CssClass="TableFramed">
<Columns>
<asp:TemplateField HeaderText="Type">
<ItemTemplate>
<asp:DropDownList ID="ddlType" runat="server" AutoPostBack="true">
<asp:ListItem Value="1">Overtime</asp:ListItem>
<asp:ListItem Value="2">Temporary</asp:ListItem>
<asp:ListItem Value="3">Permanent</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:TextBox ID="txtFName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="FNameValidator" runat="server" Text="*" ControlToValidate="txtFName" Display="Dynamic"></asp:RequiredFieldValidator>
</ItemTemplate>
<asp:TemplateField HeaderText="hide me">
<ItemTemplate>
<asp:TextBox ID="txtHideMe" runat="server"></asp:TextBox>
</ItemTemplate>
</Columns>
</asp:gridview>
How do i wire it up so that the txtHideMe textbox can be hidden or displayed based off of the selected value of the dropdownlist?
Codebehide:
Protected Sub ddlType_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
For Each row In GridViewUsers.Rows
Dim reqType As DropDownList = CType(row.FindControl("ddlType"), DropDownList)
Dim txtHideMeAs TextBox = CType(row.FindControl("txtHideMe"), TextBox)
If reqType.SelectedItem.Value = "2" Then
txtHideMe.Visible = "False"
End If
Next
End Sub
Edit:
I would also like to be able to use a required field validator on the textbox if it's not hidden.

It looks like you need to bind the SelectedIndexChanged event to the control:
<asp:DropDownList runat="server" ID="ddlType" OnSelectedIndexChanged="ddlType_SelectedIndexChanged" ...>

Related

asp vb gridview changes the input value by it self

I'm using asp.net web form gridview and I run into a problem when inserting a new record from footer.
my footer has the different input that should be submitted but when I submit the record they change.
for example, I have an input fname if I type the name "Issa" I get it like this ",Issa"
the "," character is being added and I don't know why
this is how I retrieve the record.
Dim fname As String = TryCast(staffs_gridvw.FooterRow.FindControl("footer_sfname_txtbox"), TextBox).Text.Trim
and this is how my templet field looks like.
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label runat="server" Text='<%#Eval("sfname") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="sfname_txtbox" CssClass="form-control" runat="server" Text='<%#Eval("sfname") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="footer_sfname_txtbox" CssClass="form-control" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
any suggestion on how can I fix this issue???
Hum, I am un-able to re-produce this error.
My markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowFooter="true">
<Columns>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label runat="server" Text='<%#Eval("FirstName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="sfname_txtbox" CssClass="form-control" runat="server" Text='<%#Eval("FirstName") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="footer_sfname_txtbox" CssClass="form-control" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Button" />
My code to fill:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadGrid
End If
End Sub
Sub LoadGrid()
Dim rstData As DataTable
rstData = MyRst("SELECT * FROM tblHotelsA ORDER BY HotelName")
GridView1.DataSource = rstData
GridView1.DataBind()
End Sub
We now get this:
So I type in hello world into that text box, hit the button, with this code:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim fname As String = TryCast(GridView1.FooterRow.FindControl("footer_sfname_txtbox"), TextBox).Text.Trim
Debug.Print(fname)
End Sub
And I see this:
So, I guess the question is what other operations are you doing to that GV?
Edit: Button is also in the the GV footer
Ok, so then we have this:
<div style="padding:25px;width:20%">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowFooter="true" CssClass="table">
<Columns>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label runat="server" Text='<%#Eval("FirstName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="sfname_txtbox" CssClass="form-control" runat="server" Text='<%#Eval("FirstName") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="footer_sfname_txtbox" CssClass="form-control" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hotel">
<ItemTemplate>
<asp:Label ID="lblHotel" runat="server" Text='<%#Eval("HotelName") %>' ></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="Button2" runat="server" Text="Button" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
And code to load - same as before.
So, now we see this:
Of course, the button is now in the GV - so I can't double click to wire up a event, but you of course then use markup.
Type in onclick= (hit ctrl-space bar under the quotes) - and then you get this option:
Ok, so now we have our event behind.
This code:
Protected Sub Button2_Click(sender As Object, e As EventArgs)
Dim fname As String = TryCast(GridView1.FooterRow.FindControl("footer_sfname_txtbox"), TextBox).Text.Trim
Debug.Print(fname)
End Sub
And now this:
And click on button, I see/get this:

Error while binding data in GridView through Row Bound Event

I have following gridview in aspx page:
<asp:GridView Runat="server" id="gv1" PageSize="20" Visible="False" AllowPaging="True" Width="100%"
CssClass="clsDataGrid" AutoGenerateColumns="false" DataKeyNames="intProofSLNo,txtAdminRemarks" CommandArgument='Eval(intProofSLNo,txtAdminRemarks)'
OnRowCommand="gv1_RowCommand" OnRowDataBound ="gv1_OnRowDataBound" >
<asp:BoundField DataField="intProofSLNo" ReadOnly="True" Visible="false" ItemStyle-Wrap="false" HeaderText="Sl No" ItemStyle-CssClass="clsNormalText"></asp:BoundField>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="lnkbtnApprove" runat="server" CommandName="Approve" Text= "Approve / " />
<asp:LinkButton ID="lnkbtnReject" runat="server" CommandName="Reject" Text= "Reject" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Admin Remarks">
<ItemTemplate>
<asp:Label ID="lblAdminRemarks" runat="server" ItemStyle-Wrap="True" Text='<%# Bind("txtAdminRemarks")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAdminRemarksEdit" runat="server" cssclass=clsCommonInput MaxLength="252" Text='<%# DataBinder.Eval(Container.DataItem, "txtAdminRemarks")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="lblEdit" runat="server" Text="Edit" ToolTip="Edit" CommandName="Edit" CommandArgument='<%# Container.DataItemIndex %>'>
</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" Width="38" runat="server" Text="Update|" CommandName="Update"CommandArgument='<%# Container.DataItemIndex %>' CausesValidation="true" ToolTip="Save"> </asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" Width="40" Text="Cancel" CommandName="Cancel"
CausesValidation="false" ToolTip="Reset"></asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The user clicks on the 'Edit' link which makes 'Update' and 'Cancel' links visible.It then enters the remarks in the textbox and clicks 'Update'.A row command event is fired which updates the remarks in DB for the entry in that particular row. The same event calls the bind function:
Protected Sub gv1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
If e.CommandName = "Update" Then
//some code to update remarks//
gv1.EditIndex = -1
subBindDataGrid()
End If
The subBindDataGrid() fires the following rowbound event which hides the buttons depending on admin remarks:
Protected Sub gv1_OnRowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim lblAdminRemarks As Label = DirectCast(e.Row.FindControl("lblAdminRemarks"), Label)
Dim lnkReject As LinkButton = DirectCast(e.Row.FindControl("lnkbtnReject"), LinkButton)
Dim lnkApprove As LinkButton = DirectCast(e.Row.FindControl("lnkbtnApprove"), LinkButton)
Dim lnkEdit As LinkButton = DirectCast(e.Row.FindControl("lblEdit"), LinkButton)
If DataBinder.Eval(e.Row.DataItem, "txtAdminRemarks").ToString().Trim = "Auto-Approved" Then
lnkApprove.Visible = False
lnkReject.Visible = False
lnkEdit.Visible = False
Else
lnkbtnApprove.Visible = True
lnkbtnReject.Visible = True
End If
End If
The remarks get updated in the DB. However, there is some issue in binding and instead of displaying the grid, the page is redirected to an error page. There is no exception thrown anywhere while debugging. The same events are also called in 'Edit'command. However, the functionality works fine there.Please suggest if there is anything wrong with the syntax.
I see you don't define a DataSourceID on the GridView static definition, please make sure you define a DataSource for the GridView in the subBindDataGrid procedure, otherwise it will have a null datasource in input.

Need help setting the same values for radiobutton list in gridview in ItemTemplate based on selected value radiobuttion list in HeaderTemplate

i've been tasked to create a Gridview in which a user click a radiobutton list on the header (rblDifficulty) and all the radiobutton list in the rows below (rblDiff) will be set to the same values. I've looked and modify examples using checkboxes and jquery but without success. Hope someone can guide me on this
<asp:GridView ID="gvData" runat="server" EmptyDataText="No Data" DataKeyNames="ID" AllowPaging="true" PageSize ="15"
class="" AutoGenerateColumns="False" OnPageIndexChanging="OnPaging">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%# Eval("ID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Difficulty">
<HeaderTemplate>
<asp:RadioButtonList ID="rblDifficulty" runat="server">
<asp:ListItem Text="Easy" Value="0"></asp:ListItem>
<asp:ListItem Text="Medium" Value="Y"></asp:ListItem>
<asp:ListItem Text="Hard" Value="F"></asp:ListItem>
</asp:RadioButtonList>
</HeaderTemplate>
<ItemTemplate>
<asp:RadioButtonList ID="rblDiff" runat="server">
<asp:ListItem Text="Easy" Value="0"></asp:ListItem>
<asp:ListItem Text="Medium" Value="Y"></asp:ListItem>
<asp:ListItem Text="Hard" Value="F"></asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
UPDATE: jomsk1e helped me on this
Protected Sub rblDifficulty_onChanged(sender As Object, e As EventArgs)
Dim rblDifficulty As RadioButtonList = DirectCast(gvData.HeaderRow.FindControl("rblDifficulty"), RadioButtonList)
Dim selectedValue__1 As String = rblDifficulty.SelectedValue
For Each row In gvData.Rows
Dim rbl As RadioButtonList = DirectCast(row.FindControl("rblDiff"), RadioButtonList)
rbl.SelectedValue = selectedValue__1
Next
End Sub
Try this, using server side processing:
<asp:RadioButtonList ID="rblDifficulty" runat="server" AutoPostBack="true" OnSelectedIndexChanged="rblDifficulty_onChanged">
<asp:ListItem Text="Easy" Value="0"></asp:ListItem>
<asp:ListItem Text="Medium" Value="Y"></asp:ListItem>
<asp:ListItem Text="Hard" Value="F"></asp:ListItem>
</asp:RadioButtonList>
protected void rblDifficulty_onChanged(object sender, EventArgs e)
{
RadioButtonList rblDifficulty = (RadioButtonList)gvData.HeaderRow.FindControl("rblDifficulty");
string selectedValue = rblDifficulty.SelectedValue;
foreach (gvData row in gvData.Rows)
{
RadioButtonList rbl = (RadioButtonList)row.FindControl("rblDiff");
rbl.SelectedValue = selectedvalue;
}
}
Not tested, but will definitely give you a hint how to do it. Good luck! :)

FindControl throwing NullReferenceException

Within my ASP gridview, I have the following (updated to show full gridview):
<asp:GridView ID="TPAnnuity_GridView" AllowSorting="true" AllowPaging="true" Runat="server"
DataSourceID="TPAnnuity_SqlDataSource" DataKeyNames="AnnuityTotalPointsID"
AutoGenerateColumns="False" ShowFooter="true" PageSize="20">
<Columns>
<asp:TemplateField HeaderText="Company" SortExpression="CompanyName" HeaderStyle-VerticalAlign="Bottom">
<ItemTemplate>
<asp:Label ID="Label11" runat="server" Text='<%# Bind("CompanyName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="EditACompanyID" runat="server" DataSource="<%# ddlCompanyDS %>" DataValueField="CompanyID" DataTextField="CompanyName" selectedValue='<%# Bind("CompanyID") %>'></asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="NewCompanyID" runat="server" DataSource="<%# ddlCompanyDS %>" DataValueField="CompanyID" DataTextField="CompanyName"></asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator11" runat="server" ControlToValidate="NewCompanyID" Display="Dynamic" ForeColor="" ErrorMessage="You must enter a value. *" Enabled="false"></asp:RequiredFieldValidator>
</FooterTemplate>
<FooterStyle Wrap="False" />
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<br />
<i>No Commission Data to display.</i>
<br />
<br />
</EmptyDataTemplate>
</asp:GridView>
And within my back end, I have the following:
Sub TPAnnuity_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles TPAnnuity_GridView.RowCommand
If e.CommandName = "Cancel" Then
'Reset Footer Row input fields
CType(TPAnnuity_GridView.FooterRow.FindControl("NewCompanyID"), DropDownList).SelectedIndex = 0
ElseIf e.CommandName = "Insert" Then
TPAnnuity_SqlDataSource.InsertParameters.Clear()
Dim test1 As New Parameter("CompanyIDInt", TypeCode.Int32)
test1.DefaultValue = CType(TPAnnuity_GridView.FooterRow.FindControl("NewCompanyID"), DropDownList).SelectedValue
TPAnnuity_SqlDataSource.InsertParameters.Add(test1)
TPAnnuity_SqlDataSource.Insert()
ElseIf e.CommandName = "Update" Then
TPAnnuity_SqlDataSource.UpdateParameters.Clear()
Dim param1 As New Parameter("CompanyIDInt", TypeCode.Int32)
param1.DefaultValue = CType(TPAnnuity_GridView.FooterRow.FindControl("EditACompanyID"), DropDownList).SelectedValue ****THIS IS THE PROBLEM LINE****
TPAnnuity_SqlDataSource.UpdateParameters.Add(param1)
TPAnnuity_SqlDataSource.Update()
End If
End Sub
The Cancel and Insert functions work just fine, operating off of the footer. Every time hit the "Update" button, I get a NullReferenceException on the param1.Default Value = line.
Can anyone help me figure out what's going on here?
Your row should look like this:
param1.DefaultValue = CType(e.CommandSource.FindControl("EditACompanyID"), DropDownList).SelectedValue
Instead of utilizing the FooterRow, you have to use the source row. Since you passed that in with e, you can use this.

Without using SelectedIndexChanged, how to retrieve value of each row from gridview?

I have a GridView,
without using SelectedIndexChanged, how can I retrieve the value of each row from GridView when click on each button in each row?
this is my aspx code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID"
DataSourceID="SqlDataSource1" ShowHeader="False" AllowPaging="True" BorderColor="White"
CellPadding="6" GridLines="None" Height="100px" Width="800px">
<Columns>
<asp:TemplateField>
<ItemTemplate>
Card Name:
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
<br />
Cost :
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Price") %>'></asp:Label>
<br />
<asp:Label ID="Label3" runat="server" Text='<%# Bind("ProductImgID") %>'></asp:Label>
<asp:Image ID="Image3" runat="server" ImageUrl='<%# Eval("ProductImgUrl", "images/{0}") %>' />
<br />
<asp:Button ID="btnAddProduct" runat="server" Text="Add" />
<br />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
One option can be to Bind the CommandArgument of the button to the ProductID
<asp:Button ID="btnAddProduct" runat="server" Text="Add" CommandArgument='<%#Bind("ProductID")%>' />
and then in the RowCommand event retrieve the ProductID and extract the row from database
string prodID=(string)e.CommandArgument()
then using the ID retrieve the row from database.
To get a row value, you have to get the row Reference, After getting the row you can easily get to the specified column and can get the value
Lets Consider you have a "link button control" in a template field column. For the gridview you have to set Row Command Event, and also in the edit template of the column, set a command name for the link button also say "lnkTest"
In RowCommand Event you have to include the following section of code
if(e.CommandName.Equals("lnkTest")) // Checks that link button was clicked
{
GridViewRow grdRow = (((LinkButton)e.CommandSource).Container)
// This Will give you the reference of the Row in which the link button was clicked
int grdRowIndex = grdRow.RowIndex;
//This will give you the index of the row
var uniqueDataKeyValue = GridView1.DataKeys[grdRowIndex].Value;
//This will give you the DataKey Value for the Row in which the link Control was click
Hope the above code will help
Add CommandArgument='<%# Container.DataItemIndex %>' to your Add button
<asp:Button ID="btnAddProduct" runat="server" Text="Add" CommandArgument='<%# Container.DataItemIndex %>'/>
To retrive Name, in gridview row command use this code
Dim gvr As GridViewRow = grvGRNCONs.Rows(e.CommandArgument)
Dim name As String = DirectCast(gvr.FindControl("Label1"), Label).Text
and so on..
<asp:GridView ID="grdResults" CssClass="CommonTable dataTable" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:TemplateField HeaderText="Sl#">
<ItemTemplate>
<asp:Label ID="lblSlno" Text='<%# Container.DataItemIndex+1 %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="" ControlStyle-Height="15px" ControlStyle-Width="15px">
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" CssClass="PInfoTd" />
<ItemTemplate>
<asp:ImageButton ID="lknassesno" ToolTip="Edit Assessment" Width="50" CssClass="NewButton" ***CommandName="LINK"***
runat="server" ImageUrl="~/img/Edit.png" />
<asp:HiddenField ID="hidassesmentno" Value='<%# EVAL("PAN_CODE")%>' runat="server" />
<asp:HiddenField ID="hidPendStatus" Value='<%# EVAL("Pstatus")%>' runat="server" />
<asp:HiddenField ID="hidIPNO"Value='<%#EVAL("IP_NO")%>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
**code behind**
Protected Sub grdResults_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles grdResults.RowCommand
If **e.CommandName = "LINK"** Then
Dim ctrl As Control = e.CommandSource
Dim grrow As GridViewRow = ctrl.Parent.NamingContainer
'Dim i As Integer = Convert.ToInt16(e.CommandArgument)
'Dim lknassesno As HiddenField = DirectCast(e.CommandSource, ImageButton)
Dim hidAssesmentNo As HiddenField = DirectCast(grdResults.Rows(grrow.RowIndex).FindControl("hidassesmentno"), HiddenField)
Dim lblstatus As HiddenField = DirectCast(grdResults.Rows(grrow.RowIndex).FindControl("hidPendStatus"), HiddenField)
Dim hidIpNo As HiddenField = DirectCast(grdResults.Rows(grrow.RowIndex).FindControl("hidIPNO"), HiddenField)
Dim Assno As String = hidAssesmentNo.Value
Dim Ipno As String = hidIpNo.Value
Dim st As String = ""
If lblstatus.Value = "Pending" Then
st = "E"`enter code here`
ElseIf lblstatus.Value = "Completed" Then
st = "V"
End If
Response.Redirect("Assessment.aspx?PAssNo=" & Assno & "&Mode=" & st & "&IPNO=" & Ipno & "")
End If
End Sub

Resources