How to get the checked radio button value outputted to a label - asp.net

I am getting the output of 0 and I don't know what I am doing wrong. I using the findcontrol method to find the IDs within the Gridview and declaring them as radiobuttons, then I am trying to use an if statement to assign the checked radio button a value, then output that value to a label.
vb code
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
Dim numOutput As Integer
For Each row As GridViewRow In GridView1.Rows
Dim qID As Label = row.FindControl("QuestionID")
Dim rd1 As RadioButton = TryCast(row.FindControl("answer1"), RadioButton)
Dim rd2 As RadioButton = TryCast(row.FindControl("answer2"), RadioButton)
Dim rd3 As RadioButton = TryCast(row.FindControl("answer3"), RadioButton)
Dim rd4 As RadioButton = TryCast(row.FindControl("answer4"), RadioButton)
If rd1.Checked = True Then
numOutput = 1
ElseIf rd2.Checked = True Then
numOutput = 2
ElseIf rd3.Checked = True Then
numOutput = 3
ElseIf rd4.Checked = True Then
numOutput = 4
End If
Next
lblOutput.Text = numOutput
End Sub
Source code
<asp:GridView ShowHeader="false" AutoGenerateColumns="false" ID="GridView1" runat="server" GridLines="None">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" ID="QuestionID" Text='<%# Eval("QuestionID")%>' />
<asp:Label runat="server" ID="Question" Text='<%# Eval("Question")%>' /><br />
<asp:RadioButton GroupName="a" Text='<%# Eval("answer1")%>' runat="server" ID="answer1" /><br />
<asp:RadioButton GroupName="a" Text='<%# Eval("answer2")%>' runat="server" ID="answer2" /><br />
<asp:RadioButton GroupName="a" Text='<%# Eval("answer3")%>' runat="server" ID="answer3" /><br />
<asp:RadioButton GroupName="a" Text='<%# Eval("answer4")%>' runat="server" ID="answer4" /><hr />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
<asp:Label ID="lblOutput" runat="server" Text="" />

Your bug
I don't know what's wrong with your code because I can't debug your code for see what happens on your VB code. If you don't know how you can debug your code, please watch this YouTube video about debugging.
My suggestion
I suggest you to place all your check boxes onto a panel and loop over all the items of that control. I go check if each control is a RadioButton. if yes, cast that onto a RadioButton and check if the RadioButton is checked. If yes, counter can be display in your label.
The counter counts witch RadioButton is checked and is also the output you can show on your label. See also code for more information for what I do.
Don't forget to add one to the counter or it will stay on the same value.
Here is the VB code:
Dim counter As Integer = 0
For Each contr As Control In pnlAnswers.Controls 'loop over each control on the panel
If TypeOf contr Is RadioButton Then 'Check if contr is a RadioButton
RadioButton rdb = CType(contr, RadioButton) 'if yes cast it to a RadioButton
If rdb.Checked Then 'If checked
lblOutput.Text = counter.ToString() 'Place the tag value on the output label
Return
End If
counter += 1
End If
Next
Place also your labels outside the panel. Note that it has no impact for the code behind if the labels are inside the panel. The loop will skip them because a label is not a type of a radio button. But it beter that the labels are outside when you add some features to your application.
Here is the ASP code:
<asp:Label runat="server" ID="QuestionID" Text='<%# Eval("QuestionID")%>' />
<asp:Label runat="server" ID="Question" Text='<%# Eval("Question")%>' /><br />
<asp:panel ID="pnlAnswers" runat="server">
<asp:RadioButton GroupName="a" Text='<%# Eval("answer1")%>' runat="server" ID="answer1" /><br />
<asp:RadioButton GroupName="a" Text='<%# Eval("answer2")%>' runat="server" ID="answer2" /><br />
<asp:RadioButton GroupName="a" Text='<%# Eval("answer3")%>' runat="server" ID="answer3" /><br />
<asp:RadioButton GroupName="a" Text='<%# Eval("answer4")%>' runat="server" ID="answer4" />
</asp:panel>
P.S.: The tags I've added on a previous update aren't necessary now.
Code clean up
I've also removed this line of code:
Dim qID As Label = row.FindControl("QuestionID")
I can't find any line where you use this line so it's overkill to find your label QuestionID.
Notes
It's a long time ago I've used VB.NET and ASP.NET web forms so please comment me if the code is not working.
#SOreadytohelp

Related

Drop-Down List inside Update Panel not Triggering SelectedIndexChanged Event

I'm in Asp.net 3.5 (Visual Studio 2008, VB). In a DetailsView, I've got several controls that need to perform hide/display actions, and I'm using an Update Panel. The first control is a radio button ("rblAttemptType") with two options: Phone Call or Letter. If the user chooses Phone Call, a textbox to record the time of the call opens (there's also a textbox to record the date, but it applies to both calls and letters, so it stays visible). Choosing Phone Call also enables/disenables another radio button ("rblSuccess") that records whether the contact attempt was successful. The options for rblSuccess are N/A, No and Yes. The N/A option applies when the user chooses Letter from rblAttemptType, in which case rblSuccess is also disabled (and more fields in the DetailsView become visible).
But if the user chooses Phone Call from rblAttemptType, rblSuccess is selection-cleared and enabled. Choosing no on rblSuccess reveals a drop-down list containing explanatory options (no answer, left voicemail etc.). One of the options is Other, which is supposed to reveal a textbox to record details.
Everything works, right up until that last step. It goes like this: I choose Phone Call, and the Time textbox appears. I type in the date and the time, then select No on rblSuccess, and the drop-down list appears. But when I make a selection on the drop-down list, nothing happens; i.e. the SelectedIndexChanged event assigned to the control isn't firing. And yes, it's set to AutoPostBack="True."
So--again--the SelectedIndexChanged subs for both of the radio buttons are working fine, but the one for the drop-down list isn't being hit.
Here's the code. I'm only including the parts of the DetailsView pertinent to this issue; let me know if you want the whole thing).
From the aspx page:
<asp:DetailsView ID="dvAppointment" runat="server" AutoGenerateRows="False" DataKeyNames="aID"
Visible="False" Caption="Appointment Details" BorderColor="#189AA1" BorderStyle="Solid"
BorderWidth="1px">
<RowStyle BackColor="White" BorderStyle="None" Font-Names="Verdana,Arial,Helvetica"
Font-Size="11px" Font-Strikeout="False" />
<FieldHeaderStyle BackColor="#449c77" CssClass="white" Font-Bold="True" Width="15%"
BorderColor="#189AA1" BorderStyle="Solid" BorderWidth="1px" />
<Fields>
<asp:BoundField DataField="aID" HeaderText="aID" Visible="False" ReadOnly="True" />
<asp:TemplateField HeaderText="Attempt Type" SortExpression="AttemptType" HeaderStyle-VerticalAlign="Middle">
<ItemTemplate>
<asp:Label ID="lblAttemptType" runat="server" Text='<%# Eval("AttemptTypeDetails") %>'></asp:Label>
<br />
<asp:Label ID="lblAttemptMessage" runat="server" Text='<%# ContactAttemptMessage()%>'
HtmlEncode="False" CssClass="FireBrick9" HtmlEncodeFormatString="False" />
</ItemTemplate>
<InsertItemTemplate>
<asp:Label ID="lblAttemptMessage" runat="server" Text='<%# ContactAttemptMessage()%>'
HtmlEncode="False" CssClass="FireBrick9" HtmlEncodeFormatString="False" />
<asp:RadioButtonList ID="rblAttemptType" runat="server" RepeatDirection="Horizontal"
AutoPostBack="true" OnSelectedIndexChanged="rblAttemptTypeChanged" CssClass="Text9B">
<asp:ListItem Value="1">Phone call</asp:ListItem>
<asp:ListItem Value="2">Letter</asp:ListItem>
</asp:RadioButtonList>
</InsertItemTemplate>
<HeaderStyle VerticalAlign="Middle"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Attempt Date" SortExpression="AttemptDate">
<ItemTemplate>
<asp:Label ID="lblAttemptDateWithTime" runat="server" Text='<%# AttemptDateDetails() %>'></asp:Label>
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="txAttemptDate" runat="server" AutoCompleteType="Disabled" AutoPostBack="False"></asp:TextBox>
<asp:CalendarExtender ID="CalendarExtenderAttemptDate" runat="server" TodaysDateFormat="mm/dd/yyyy"
TargetControlID="txAttemptDate">
</asp:CalendarExtender>
<asp:UpdatePanel ID="UpdatePanelforAttempt" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="AttemptTimeLabel" runat="server" Text="Time of phone attempt (hh:mm AM/PM): "
Visible="False"></asp:Label>
<asp:TextBox ID="txAttemptTime" runat="server" ToolTip="Time should be in format XX:XX AM/PM"
Visible="False"></asp:TextBox>
<asp:MaskedEditExtender ID="txAttemptTimeTime_MaskedEditExtender" runat="server"
CultureAMPMPlaceholder="" CultureCurrencySymbolPlaceholder="" CultureDateFormat=""
CultureDatePlaceholder="" CultureDecimalPlaceholder="" CultureThousandsPlaceholder=""
CultureTimePlaceholder="" Enabled="True" TargetControlID="txAttemptTime" Mask="99:99 LL"
ClearMaskOnLostFocus="False" MaskType="Number">
</asp:MaskedEditExtender>
<asp:Label ID="LabelSuccess" runat="server" Text="<br /><br />Was the attempt successful?"
CssClass="Text8B" ></asp:Label>
<asp:RadioButtonList ID="rblSuccess" runat="server" OnSelectedIndexChanged="rblSuccessChanged"
RepeatDirection="Horizontal" AutoPostBack="True"
Enabled='<%# IIF(Eval("AttemptType")=1,"true","false") %>'>
<asp:ListItem Value="2">Yes</asp:ListItem>
<asp:ListItem Value="1">No</asp:ListItem>
<asp:ListItem Value="0" Selected="True">N/A</asp:ListItem>
</asp:RadioButtonList>
<asp:Label ID="lblNoContactReason" runat="server" Text="<br />Please clarify the contact attempt result:"
Visible="False" CssClass="smTextItalic"></asp:Label>
<asp:DropDownList ID="ddlrncType" runat="server" DataSourceID="sdsrncTypes" DataValueField="rncTypeID"
DataTextField="rncType" Visible="false" AutoPostBack="True" OnSelectedIndexChanged="ddlrncTypeChanged">
</asp:DropDownList>
<asp:Label ID="lblSpecify" runat="server" Text="<br /><br />Please Explain:<br />"
CssClass="smTextbold" Visible="False"></asp:Label>
<asp:TextBox ID="txrncOther" runat="server" Visible="false" ToolTip="Specific result (350 characters allowed)"
TextMode="MultiLine" CssClass="MultiLineInsert" Width="35%" />
</ContentTemplate>
</asp:UpdatePanel>
</InsertItemTemplate>
</asp:TemplateField>
</Fields>
<HeaderStyle BackColor="#449C77" BorderColor="#189AA1" BorderStyle="Solid" BorderWidth="1px" />
<InsertRowStyle Width="80%" BackColor="White" Font-Names="Verdana,Ariel,Helvetica"
Font-Size="11px" />
<EditRowStyle Width="77%" BackColor="White" Font-Names="Verdana,Ariel,Helvetica"
Font-Size="11px" />
<AlternatingRowStyle BackColor="#CFCFCF" Font-Names="Verdana,Ariel,Helvetica" Font-Size="11px" />
</asp:DetailsView>
From the VB code:
Protected Sub rblAttemptTypeChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim iAttemptTimeLabel As Label = DirectCast(dvAppointment.FindControl("AttemptTimeLabel"), Label)
Dim itxAttemptTime As TextBox = DirectCast(dvAppointment.FindControl("txAttemptTime"), TextBox)
Dim irblSuccess As RadioButtonList = DirectCast(dvAppointment.FindControl("rblSuccess"), RadioButtonList)
Dim iUpdatePanelforAttempt As UpdatePanel = DirectCast(dvAppointment.FindControl("UpdatePanelforAttempt"), UpdatePanel)
Dim AttemptType As Integer = 0
If Not sender.selectedValue = String.Empty Then
AttemptType = CInt(sender.selectedValue)
ViewState("AttemptType") = CInt(sender.selectedValue)
If AttemptType = 1 Then 'Phone
If Not iAttemptTimeLabel Is Nothing Then
iAttemptTimeLabel.Visible = True
End If
If Not itxAttemptTime Is Nothing Then
itxAttemptTime.Visible = True
End If
If Not irblSuccess Is Nothing Then
irblSuccess.Enabled = True
irblSuccess.ClearSelection()
End If
ElseIf AttemptType = 2 Then 'Letter
If Not iAttemptTimeLabel Is Nothing Then
iAttemptTimeLabel.Visible = False
End If
If Not itxAttemptTime Is Nothing Then
itxAttemptTime.Visible = False
End If
If Not irblSuccess Is Nothing Then
irblSuccess.Enabled = False
irblSuccess.SelectedIndex = 2
End If
End If
If Not iUpdatePanelforAttempt Is Nothing Then
iUpdatePanelforAttempt.Update()
End If
End If
End Sub
Protected Sub rblSuccessChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim iddlrncType As DropDownList = DirectCast(dvAppointment.FindControl("ddlrncType"), DropDownList)
Dim itxrncOther As TextBox = DirectCast(dvAppointment.FindControl("txrncOther"), TextBox)
Dim ilblNoContactReason As Label = DirectCast(dvAppointment.FindControl("lblNoContactReason"), Label)
Dim iUpdatePanelforAttempt As UpdatePanel = DirectCast(dvAppointment.FindControl("UpdatePanelforAttempt"), UpdatePanel)
Dim Success as Integer = -1
If Not sender.selectedValue = String.Empty Then
Success = CInt(sender.selectedValue)
If Success = 1 Then
If Not iddlrncType Is Nothing Then
iddlrncType.Visible = True
End If
If Not ilblNoContactReason Is Nothing Then
ilblNoContactReason.Visible = True
End If
Else
If Not iddlrncType Is Nothing Then
iddlrncType.Visible = False
End If
If Not ilblNoContactReason Is Nothing Then
ilblNoContactReason.Visible = False
End If
End If
If Not iUpdatePanelforAttempt Is Nothing Then
iUpdatePanelforAttempt.Update()
End If
End If
End Sub
Protected Sub ddlrncTypeChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim ilblSpecify As Label = CType(dvAppointment.FindControl("lblSpecify"), Label)
Dim itxrncOther As TextBox = CType(dvAppointment.FindControl("txrncOther"), TextBox)
Dim iUpdatePanelforAttempt As UpdatePanel = DirectCast(dvAppointment.FindControl("UpdatePanelforAttempt"), UpdatePanel)
Dim rncTypeID as Integer = 0
If Not sender.selectedValue = String.Empty AndAlso IsNumeric(sender.selectedvalue) Then
rncTypeID = CInt(sender.selectedValue)
If rncTypeID = 5 Then
If Not itxrncOther Is Nothing Then
itxrncOther.Visible = True
itxrncOther.Focus()
If Not ilblSpecify Is Nothing Then
ilblSpecify.Visible = True
End If
End If
Else
If Not itxrncOther Is Nothing Then
itxrncOther.Visible = False
If Not ilblSpecify Is Nothing Then
ilblSpecify.Visible = False
End If
End If
End If
If Not iUpdatePanelforAttempt Is Nothing Then
iUpdatePanelforAttempt.Update()
End If
End If
End Sub
I tried adding a second Update Panel, just around the drop-down list and the "Other" textbox, with the drop-down assigned as the AsyncPostBackTrigger, but it didn't make a difference.

How to find Radio button control within Gridview

I am trying to find a radiobutton control within a gridview but I keep getting the output of 0 for whatever radiobutton I select. I want each radiobutton to be assigned the value of 1-4 and then whatever radiobutton selected, it will be outputted to a label.
VB code
Dim SelectNumber As Integer
For Each row As GridViewRow In MyGridView.Rows
Dim radbtn1 As RadioButton = TryCast(row.FindControl("a1"), RadioButton)
Dim radbtn2 As RadioButton = TryCast(row.FindControl("a2"), RadioButton)
Dim radbtn3 As RadioButton = TryCast(row.FindControl("a3"), RadioButton)
Dim radbtn4 As RadioButton = TryCast(row.FindControl("a4"), RadioButton)
If radbtn1.Checked = True Then
SelectNumber = 1
ElseIf radbtn2.Checked = True Then
SelectNumber = 2
ElseIf radbtn3.Checked = True Then
SelectNumber = 3
ElseIf radbtn4.Checked = True Then
SelectNumber = 4
End If
Next
lblOutput.Text = SelectNumber
Source code
<asp:GridView ShowHeader="false" AutoGenerateColumns="false" ID="MyGridView" runat="server" GridLines="None">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" ID="QuestionID" Text='<%# Eval("QuestionID")%>' />
<asp:Label runat="server" ID="Question" Text='<%# Eval("Question")%>' /><br />
<asp:RadioButton GroupName="gnA" Text='<%# Eval("a1")%>' runat="server" ID="ans1" /><br />
<asp:RadioButton GroupName="gnA" Text='<%# Eval("a2")%>' runat="server" ID="ans2" /><br />
<asp:RadioButton GroupName="gnA" Text='<%# Eval("a3")%>' runat="server" ID="ans3" /><br />
<asp:RadioButton GroupName="gnA" Text='<%# Eval("a4")%>' runat="server" ID="ans4" /><hr />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnSubmit" runat="server" Text="Complete" />
<asp:Label ID="lblOutput" runat="server" Text="" />
I'm pretty sure that the reason for this issue is that you databind the grid on every postback instead of only If Not Page.IsPostback. Then no one is checked and the SelectNumber keeps it's default value which is 0
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
' DataBind the GridView here or call a method therefore '
End If
End Sub

ASP.Net GridView DropDownList not posting back with updated data

I have a GridView that contains DropDownLists. They function as expected except during page postback. When the user clicks the update button on the page, I have a sub that loops through the grid rows, performs business ops and saves the data.
The problem is that during postback, the DropDownLists' selected properties do not represent that changes to selections made by the user. The selected item shows 'Dirty = True' in the break point.
Here is a subset of the code I use for reference:
<asp:GridView ID="materialGridView" runat="server"
AutoGenerateColumns="false" >
<Columns>
<asp:BoundField DataField="MaterialTypeName" HeaderText="Material Type" />
<asp:TemplateField>
<HeaderTemplate>
Quantity
</HeaderTemplate>
<ItemTemplate>
<asp:TextBox ID="quantityTextBox" runat="server" Width ="50" ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Material
</HeaderTemplate>
<ItemTemplate>
<asp:DropDownList ID="materialDropDownList" runat="server" Width="200">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Color
</HeaderTemplate>
<ItemTemplate>
<asp:TextBox ID="colorTextBox" runat="server" Width="100" BackColor="BlanchedAlmond" ReadOnly="true" ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
RBK
</HeaderTemplate>
<ItemTemplate>
<asp:RadioButton id="rbkRadioButton" runat="server" Checked="true" />
<asp:TextBox ID="rbkPriceTextBox" runat="server" Width="50" ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Wimsatt
</HeaderTemplate>
<ItemTemplate>
<asp:TextBox ID="wimsattPriceTextBox" runat="server" Width="50"></asp:TextBox>
<asp:RadioButton id="wimsattRadioButton" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
For Each row As GridViewRow In materialGridView.Rows
With row
materialDropDownList = DirectCast(.FindControl("materialDropDownList"), DropDownList)
quantityTextBox = DirectCast(.FindControl("quantityTextBox"), TextBox)
rbkPriceTextBox = DirectCast(.FindControl("rbkPriceTextBox"), TextBox)
wimsattPriceTextBox = DirectCast(.FindControl("wimsattPriceTextBox"), TextBox)
colorTextBox = DirectCast(.FindControl("colorTextBox"), TextBox)
rbkRadioButton = (DirectCast(.FindControl("rbkRadioButton"), RadioButton))
'compare current selecton in drop down and update if nessisary
For Each materialTableRow As DataRow In materialTable.Rows
'the item we are on is the item selected ANDALSO it is not yet assigned to the quote, so it's a new selection, update pricing.
Dim materialTableRowMaterialID As String = bizClass.dbCStr(materialTableRow.Item("MaterialID"))
If materialTableRowMaterialID = materialDropDownList.SelectedValue Then
If IsDBNull(materialTableRow.Item("QuoteID")) Then
rbkPriceTextBox.Text = bizClass.dbCStr(materialTableRow.Item("RBK"))
wimsattPriceTextBox.Text = bizClass.dbCStr(materialTableRow.Item("Wimsatt"))
End If
End If
Next materialTableRow
If rbkRadioButton.Checked = True Then
materialCostSumDecimal += bizClass.strToDec(quantityTextBox.Text) * bizClass.strToDec(rbkPriceTextBox.Text)
chosenSupplierString = "RBK"
Else
materialCostSumDecimal += bizClass.strToDec(quantityTextBox.Text) * bizClass.strToDec(wimsattPriceTextBox.Text)
chosenSupplierString = "Wimsatt"
End If
End With 'row
First of all make sure you are not binding the gridview on postback before reading dropdown values, because databind causes all controls to lose their postback value.
Second gridview is only able to postback the value of the only row that is being edited, so what you need to do is to move the dropdown (and all other controls) to the EditTemplate and set the row mode to Edit so the value will get posted back to server.
But if you want to be able to change all the dropdowns in all rows you might need to use Repeater control instead of GridView.

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

how to set some of the listView insertItem data manually (in code)? (simple but need help)

hi i have an insertItemTemplate as follows, and all i want to do is to programmatically add all the values myself, without asking the user, of course, the userID, picID and dateTime should not be asked to the user, the comments field of course, i want to ask the user as they are leaving a comment about a picture on the site :)... seems simple but really frustrating.
<InsertItemTemplate>
<span style="">UserID:
<asp:TextBox Visible="false" ID="UserIDTextBox" runat="server" Text='<%# Bind("UserID") %>' />
<br />CommentForPicID:
<asp:TextBox Visible="false" ID="CommentForPicIDTextBox" runat="server"
Text='<%# Bind("CommentForPicID") %>' />
<br />Comment:
<asp:TextBox TextMode="MultiLine" ID="CommentTextBox" runat="server" Text='<%# Bind("Comment") %>' />
<br />DateAdded:
<asp:TextBox Visible="false" ID="DateAddedTextBox" runat="server"
Text='<%# Bind("DateAdded") %>' />
<br />
<asp:Button ID="InsertButton" runat="server" CommandName="Insert"
Text="Insert" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel"
Text="Clear" />
<br /><br /></span>
</InsertItemTemplate>
i tried the following and it worked
Protected Sub lvComments_ItemCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewCommandEventArgs) Handles lvComments.ItemCommand
If e.Item.ItemType = ListViewItemType.InsertItem Then
Dim tb = New TextBox
tb = e.Item.FindControl("UserIDTextBox")
If tb IsNot Nothing Then
tb.Text = Request.Cookies("UserID").Value
End If
tb = Nothing
tb = e.Item.FindControl("CommentForPicIDTextBox")
If tb IsNot Nothing Then
tb.Text = Request.Cookies("ShownPicID").Value
End If
tb = Nothing
tb = e.Item.FindControl("DateAddedTextBox")
If tb IsNot Nothing Then
tb.Text = DateTime.Now.ToString
End If
tb = Nothing
End If
End Sub
you can do it on the ItemCreated event, but then it alters the data sent to the browser, and then this data is going to be sent back (unnecessary round trip), so i did it on ItemCommand, which is when you receive the command, the code is exactly the same and will work on both of the events mentioned!!

Resources