DetailsView can't figure how to trigger update event - asp.net

I've been trying to make use of DetailsView for the past few days to show and edit data from a single record taken from a GridView, both read their datafrom an SqlDataSource.
I've been searching the internet and the MSDN for info about how to use a DetailsView to edit data and I managed to cobble something together, the problem is that apparently the actual updating method doesn't run.
So here's an extract of my code
GridView In the page:
<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px" AutoGenerateRows="False" DefaultMode="Edit">
<fields>
<asp:TemplateField HeaderText="Codice Cliente">
<ItemTemplate>
<asp:Label ID="lblCliCod" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.cli_cod") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCliCod" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.cli_cod")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Descrizione">
<ItemTemplate>
<asp:Label ID="lblCliDesc" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.cli_desc")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCliDesc" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.cli_desc")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Nome Utente">
<ItemTemplate>
<asp:Label ID="lblCliUser" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.cli_user")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCliUser" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.cli_user")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Password">
<ItemTemplate>
<asp:Label ID="lblCliPass" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.cli_pass")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCliPass" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.cli_pass")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amministratore">
<ItemTemplate>
<asp:Label ID="lblCliAdmin" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.cli_admin")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="chkCliAdminE" runat="server" Text='<%# CBool(DataBinder.Eval(Container, "DataItem.cli_admin"))%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<EditItemTemplate>
<asp:LinkButton Text="Aggiorna" ID="UpdateButton" runat="Server" CommandName="Update"></asp:LinkButton>
<asp:LinkButton Text="Elimina" ID="DeleteButton" runat="server" CommandName="Edit"></asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
</fields>
</asp:DetailsView>
Relevant parts of the Codebehind:
Private Sub SetupDataSource() 'this is the sqldatasource I'm using for the detailsview
SqlDataSource2.ConnectionString = Assist.connectionString
SqlDataSource2.SelectCommand = detailsSelect
SqlDataSource2.SelectParameters.Add(New Parameter("id"))
SqlDataSource2.UpdateCommand = detailsUpdate
SqlDataSource2.UpdateParameters.Add(New Parameter("cli_cod"))
SqlDataSource2.UpdateParameters.Add(New Parameter("cli_desc"))
SqlDataSource2.UpdateParameters.Add(New Parameter("cli_user"))
SqlDataSource2.UpdateParameters.Add(New Parameter("cli_pass"))
SqlDataSource2.UpdateParameters.Add(New Parameter("cli_admin"))
End Sub
Private Sub SetupDetailsView(id As Int32)
DetailsView1.AutoGenerateRows = False
DetailsView1.DataSource = SqlDataSource2
SqlDataSource2.SelectParameters("id").DefaultValue = id
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
cn.Open()
SetupDataSource()
If Not IsPostBack Then
Dim id As String = Request.QueryString("id")
If id <> "" Then
SetupDetailsView(id)
DetailsView1.DataBind()
End If
End If
End Sub
Protected Sub DetailsView1_ItemUpdating(sender As Object, e As DetailsViewUpdateEventArgs) Handles DetailsView1.ItemUpdating
Dim cliCod As String = (CType(DetailsView1.FindControl("txtCliCod"), TextBox)).Text.ToString()
Dim cliDesc As String = (CType(DetailsView1.FindControl("txtCliDesc"), TextBox)).Text.ToString()
Dim cliUser As String = (CType(DetailsView1.FindControl("txtCliUser"), TextBox)).Text.ToString()
Dim cliPass As String = (CType(DetailsView1.FindControl("txtCliPass"), TextBox)).Text.ToString()
Dim cliAdmin As Boolean = If((CType(DetailsView1.FindControl("chkCliAdminE"), CheckBox)).Checked = True, True, False)
SqlDataSource2.UpdateParameters("cli_cod").DefaultValue = cliCod
SqlDataSource2.UpdateParameters("cli_desc").DefaultValue = cliDesc
SqlDataSource2.UpdateParameters("cli_user").DefaultValue = cliUser
SqlDataSource2.UpdateParameters("cli_pass").DefaultValue = cliPass
SqlDataSource2.UpdateParameters("cli_Admin").DefaultValue = If(cliAdmin = True, "1", "0")
DetailsView1.DataBind()
End Sub
I'm either missing something or doing it wrong somewhere, which one is it and why?

I'm not an expert at using SqlDataSource, but you might try inserting a SqlDataSource.Update in your Item_Updating method:
SqlDataSource2.UpdateParameters("cli_cod").DefaultValue = cliCod
SqlDataSource2.UpdateParameters("cli_desc").DefaultValue = cliDesc
SqlDataSource2.UpdateParameters("cli_user").DefaultValue = cliUser
SqlDataSource2.UpdateParameters("cli_pass").DefaultValue = cliPass
SqlDataSource2.UpdateParameters("cli_Admin").DefaultValue = If(cliAdmin = True, "1", "0")
SqlDataSource2.Update();
DetailsView1.DataBind()

I use a DetailsView in an ongoing project. They are finicky, but they work great when set up correctly.
Several potential issues I can see with your DetailsView are:
Eval vs Bind
As with all databound controls, Databinder.Eval is a read-only databind method. To allow controls to automatically update, you must use Bind in the edit template. Of course, you can manually update your database, but why reinvent the wheel?
<asp:TemplateField HeaderText="Codice Cliente">
<ItemTemplate>
<asp:Label ID="lblCliCod" runat="server" Text='<%# Eval("DataItem.cli_cod") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCliCod" runat="server" Text='<%# Bind("DataItem.cli_cod")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
Built-in Update functionality vs manual update functionality
You don't really need to use DetailsView1_ItemUpdating unless you are want to catch and modify values after submit and before committing to the datasource. i.e. concatenating individual year/month/day textboxes into a single date.
However, since you are not currently generating an Update button (using property AutoGenerateEditButton="True"), you may need to handle the update manually as you are attempting. Alternatively, for basic binding and update, I would comment out the updating functions, add the autogenerateeditbutton="True" property, and then try updating.
Primary Key
With some datasources, you must specify the DataKeyNames property (your primary key/s of your datasource) on the DetailsView to enable auto-binding. I don't know for sure, but you may also need to set the DefaultMode property.
All properties and methods are explained well on the MSDN DetailsView page, but it's rather verbose. The MSDN Updating a DetailsView page is more concise

Related

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.

Not able to sort in GridView that uses a DataSet in VB.NET

I'm trying to sort a GridView that has 6 columns that are databound by a DataSet. All of this data is being called through a stored procedure. I've looked through the different posts and tutorials out on the interweb and finally got what I thought would be the best one for my page. But with this one, I keep getting an error,
Exception Type: System.IndexOutOfRangeException
Message: Cannot find column LoanOfficer
I'm open to help on this method or even suggestions a different way to tackle sorting.
Here is my code:
ASPX
<asp:GridView ID="dgvBranchChange" runat="server" AutoGenerateColumns="False" AllowPaging="True"
CssClass="ReportDataGrid" HeaderStyle-CssClass="DataGridHeader" RowStyle-CssClass="AccentShade"
AlternatingRowStyle-CssClass="NoShade" SelectedRowStyle-CssClass="AccentLvl3"
PagerSettings-Mode="NumericFirstLast" PagerStyle-HorizontalAlign="center" PagerStyle-CssClass="paging"
Width="100%" PageSize="25" AllowSorting="True" ShowHeaderWhenEmpty="true" OnSorting="dgvBranchChange_Sorting">
<AlternatingRowStyle CssClass="NoShade"></AlternatingRowStyle>
<Columns>
<asp:TemplateField HeaderText="LoanOfficerID" Visible="false" SortExpression="LoanOfficerID">
<ItemTemplate>
<asp:Label ID="lblBULOID" runat="server" Text='<%# Eval("LO_ID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LoanOfficer" HeaderStyle-HorizontalAlign="Center" SortExpression="LoanOfficer">
<ItemTemplate>
<asp:Label ID="lblBULOName" runat="server" Text='<%# Eval("LO_Name")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Branch_NameID" Visible="false" SortExpression="Branch_NameID">
<ItemTemplate>
<asp:Label ID="lblBUBranchID" runat="server" Text='<%# Eval("Branch_ID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Branch" HeaderStyle-HorizontalAlign="Center" SortExpression="Branch">
<ItemTemplate>
<asp:Label ID="lblBUBranchName" runat="server" Text='<%# Eval("Branch_Name")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Move_Begin_Date" HeaderStyle-HorizontalAlign="Center" SortExpression="Move_Begin_Date">
<ItemTemplate>
<asp:Label ID="lblBUBeginDate" runat="server" Text='<%# string.format("{0:MMM yyyy}",Eval("Begin_Date"))%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Move_End_Date" HeaderStyle-HorizontalAlign="Center" SortExpression="Move_End_Date">
<ItemTemplate>
<asp:Label ID="lblBUEndDate" runat="server" Text='<%# string.format("{0:MMM yyyy}",Eval("End_Date"))%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="User_who_Added_Change" HeaderStyle-HorizontalAlign="Center" SortExpression="User_who_Added_Change">
<ItemTemplate>
<asp:Label ID="lblBUUserId" runat="server" Text='<%# Eval("User_ID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Change_Date" HeaderStyle-HorizontalAlign="Center" SortExpression="Change_Date">
<ItemTemplate>
<asp:Label ID="lblBUCreationDate" runat="server" Text='<%# string.format("{0:MM/dd/yyyy}",Eval("Create_Date"))%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Link" HeaderText="Remove Change" ShowDeleteButton="true"
DeleteText="Remove" />
</Columns>
</asp:GridView>
Code Behind
Protected Sub dgvBranchChange_Sorting(sender As Object, e As GridViewSortEventArgs)
'Retrieve the current table
Dim dsBranchChange As DataSet
Dim asParams(0) As IDbDataParameter
Dim lDB As New RHubCoreFunctions.RHubDB
asParams(0) = lDB.dpCreateDataParameter("#AccountID", DbType.String, 8, AccountSelected.AccountID)
dsBranchChange = lDB.GetDataSet("ssp_Account_LO_Branch_Change", asParams)
Dim dt As DataView = dsBranchChange.Tables(0).AsDataView
If dt IsNot Nothing Then
'sort the data
If (dgvBranchChange.SortDirection() = SortDirection.Ascending) Then
dt.Sort = e.SortExpression & " ASC"
Else
dt.Sort = e.SortExpression & " DESC"
End If
dgvBranchChange.DataSource = dt
dgvBranchChange.DataBind()
End If
End Sub
EDIT:
I found out that I was using the wrong SortExpression. I was using the same one as the header text as thats what was given in pretty much all the walkthroughs/tutorials. But it has to be the same name as the column name from the table that you're getting the data from, i.e the SQL table.
But now I can only sort the first column in Ascending, nothing more
Because you have to save last sort expression in Session.
Please check link below for more information,code is in C# but you easily can convert to VB.
GridView sorting: SortDirection always Ascending
I hope help you.

GridView and Hidden Fields

I've got a Web app, in VB/ASPX, with a GridView fill with a SqlDataSource in my aspx file. Like this :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" SkinID="dataGrid" onrowcommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField AccessibleHeaderText="id_session" HeaderText="id_session">
<EditItemTemplate>
<asp:TextBox ID="txt_id_session" runat="server" Text='<%# Bind("id_session") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbl_id_session" runat="server" Text='<%# Bind("id_session") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Formation_2014ConnectionString %>"
SelectCommand="SELECT s.id_session, f.libelle_formation, s.date_debut_session, s.date_fin_session, COUNT(p.id_personne) AS Expr1 FROM Sessions AS s LEFT OUTER JOIN Participe AS p ON p.id_session = s.id_session AND p.actif = 1 RIGHT OUTER JOIN Formation AS f ON f.id_formation = s.id_formation WHERE (s.date_fin_session > GETDATE()) OR (s.date_fin_session < GETDATE()) OR (S.date_fin_session = GETDATE()) GROUP BY s.id_session, f.libelle_formation, s.date_debut_session, s.date_fin_session" >
</asp:SqlDataSource>
This parts works, after that I'm hiding the first column, "id_session" with this code in my CodeBehind :
Protected Sub OnRowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles GridView1.RowCreated
GridView1.Columns(0).Visible = False
'e.Row.Cells(0).Visible = False 'This way delete my paging
(RequĂȘte)
End Sub
And after that, I have to get the value of this Hidden column in my vb code, i'm trying different way but nothing ><
Dim id_session = GridView1.SelectedRow.Cells(0).Controls(0).ToString 'Return System.Web.UI.Literalcontrol
Dim id_session = GridView1.SelectedRow.RowIndex 'Return number of line
Sorry for my english, i'm French !
use the Hiddenfield
try the following code insted of useing textbox in the firest column
<asp:HiddenField ID="hf_sessionId" runat="server" Value='<%# Bind("id_session") %>' />
it will not show to the UI and you can easily access the value from it
with this code you don't need the RowCreated event of the grid
dear remove this code
<ItemTemplate>
<asp:Label ID="lbl_id_session" runat="server" Text='<%# Bind("id_session") %>'></asp:Label>
</ItemTemplate>
and put the hiddenfield into the other itemtemplate which you want to display
Instead of "GridView1.Columns(0).Visible = False" change your code like this,
GridView1.Columns(0).style("display")="none"
I finally found this method :
Dim id_session = (CType(GridView1.SelectedRow.Cells(0).Controls(1), Label)).Text
It Work !

Why am I not getting any data back when I click on ImageButton in a GridView

I have the following Gridview, with an ImageButton in the last column. I am trying to return the First and Last names from the row from which the button has been clicked. I have spent several hours looking on here and other sites trying to get it to work, but with no success.
If someone could have a look at my code and see if I am doing anything wrong it would be much appreciated.
Thanks
ASP Code
<asp:GridView runat="server" ID="gvSecondaryContacts" AutoGenerateColumns="False" DataKeyNames="ContactID" ShowHeaderWhenEmpty="false" GridLines="None" OnRowCommand="gvSecondaryContacts_OnRowCommand" >
<Columns>
<asp:BoundField DataField="ContactID" HeaderText="ContactID" InsertVisible="False" ReadOnly="True" SortExpression="ContactID" Visible="false"/>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("FirstName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtSecFirstName" Text='<%# Eval("FirstName") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("LastName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtSecLastName" Text='<%# Eval("LastName") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("Email") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtSecEmail" Text='<%# Eval("Email") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Position">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("ClubPosition") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtSecClubPosition" Text='<%# Eval("ClubPosition") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton runat="server" ID="ibtnDelete" CommandName="Delete" AlternateText="Delete Contact" CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
VB Code
Public Sub gvSecondaryContacts_OnRowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
If e.CommandName = "Delete" Then
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
Dim row = gvSecondaryContacts.Rows(index)
Dim ContactID As Integer = Convert.ToInt32(gvSecondaryContacts.DataKeys(index).Value)
Dim sFirstName As String = gvSecondaryContacts.Rows(index).Cells(1).Text
Dim sLastName As String = gvSecondaryContacts.Rows(index).Cells(2).Text
MsgBox("Your name is " & sFirstName & " " & sLastName)
End If
End Sub
I have also tried the following for the ImageButton but it returned is a type and cannot be used as an expression error
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton runat="server" ID="ibtnDelete" CommandName="Delete" AlternateText="Delete Contact" CommandArgument="<%# CType(Container, GridViewRow).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
You could hanlde the click-event instead. You can cast the ImageButon's NamingContainer to GridViewRow in the click-event handler. Then you just have to use FindControl:
Protected Sub Delete(sender As Object, e As EventArgs)
Dim ctrl = DirectCast(sender, Control)
Dim row = DirectCast(ctrl.NamingContainer, GridViewRow)
' you should rename this to LblFirstName
Dim Label2 = DirectCast(row.FindControl("Label2"), Label)
' you should rename this to LblLastName
Dim Label1 = DirectCast(row.FindControl("Label1"), Label)
'MessageBoxes in ASP.NET don't make much sense
MsgBox("Your name is " & Label2.Text & " " & Label1.Text)
End Sub
I think the problem is setting CommandArgument of ImageButton
CommandArgument="<%# CType(Container, GridViewRow).RowIndex %>"
You don't have do it according to this MSDN Example. Also you (if data binding done from server side) should bind your gridview only if page is not posting back as;
If Not Page.IsPostBack Then
'Bind your gridview here
End if
try this
Dim sFirstName As String = ((Label)gvSecondaryContacts.Rows(index).Cells(1).FindControl("Label2")).Text
Dim sLastName As String =((Label)gvSecondaryContacts.Rows(index).Cells(2).FindControl("Label1")).Text

GridView not returning databound rows when OnClick event fires

I have a GridView that is made up of two database fields populated via a stored procedure and then three fields for user input (two checkbox controls and one textbox) when I click on the save button I can get the information from the three controls but nothing from the two that were populated via the database. How can I get the first two fields?
<asp:GridView ID="gvA1" runat="server" AutoGenerateColumns="false" DataKeyNames="CodeNo" AutoGenerateSelectButton="false" EnablePersistedSelection="True" Visible="false">
<Columns>
<asp:TemplateField Visible="false" >
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem, "CodeNo")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Wrap="true" ItemStyle-Width="400px" HeaderText="Violation">
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem, "CodeViolationCited") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="A1Accordion_cbPool" runat="server" Text="Pool:" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="A1Accordion_cbSpa" runat="server" Text="Spa:" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Additional Comments" Visible="true">
<ItemTemplate>
<asp:TextBox ID="A1Accordion_tb" runat="server" TextMode="MultiLine"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind:
protected void SaveAndCollapseA1(object sender, EventArgs e)
{
//good stuff
CheckBox myCheckBox_1 = gvA1.Rows[0].FindControl("A1Accordion_cbPool") as CheckBox;
CheckBox myCheckBox_2 = gvA1.Rows[0].FindControl("A1Accordion_cbSpa") as CheckBox;
TextBox myTextBox = gvA1.Rows[0].FindControl("A1Accordion_tb") as TextBox;
//not so good stuff
String myString1 = gvA1.Rows[0].Cells[0].ToString();
String myString2 = gvA1.Rows[0].Cells[1].ToString();
}
I figured it out but I haven't been hear long enough to post the solution via the links but if you change the columns as so:
<asp:label ID="lblA1CodeNo" runat="server" text='<%# Eval("CodeNo") %>'></asp:label>
then the values are available...
Try:
<%# Bind("CodeViolationCited") %>
Instead of
<%#DataBinder.Eval(Container.DataItem, "CodeViolationCited") %>
Eval is one way, bind is two-way.
See Microsoft's documentation for data-binding expressions

Resources