I have the following aspx code;
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ProductId"
DataSourceID="edsinventory" OnRowCommand="GridView1_RowCommand"
ShowFooter="true" CssClass="mGrid">
<Columns>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True"
CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate><asp:LinkButton ID="LinkButton3" runat="server" CommandName="Insert">Insert</asp:LinkButton></FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Id" InsertVisible="False"
SortExpression="Id">
<EditItemTemplate>
<asp:Label ID="lblEditId" runat="server" Text='<%# Eval("Id") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# Bind("Id")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProductId" SortExpression="ProductId">
<EditItemTemplate>
<asp:TextBox ID="tbProdId" Width="50" runat="server" Text='<%# Bind("ProductId")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="tbInsertProdId" Width="50" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblProdId" runat="server" Text='<%# Bind("ProductId")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
'shortened for brevity
</Columns>
</asp:GridView>
here is the code behind
Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
' This just provides easier access to the Cells in the GridView
Dim cells = GridView1.FooterRow.Cells
Dim ctx As New teckEntities()
Dim addInventory As New inventory()
If e.CommandName = ("Insert") Then
'Create new Inventory object
addInventory.ProductId = Convert.ToInt32(DirectCast(cells(3).FindControl("tbInsertProdId"), TextBox).Text)
addInventory.Quantity = Convert.ToInt32(DirectCast(cells(4).FindControl("tbInsertQuantity"), TextBox).Text)
addInventory.Location = Convert.ToString(DirectCast(cells(1).FindControl("tbInsertLocation"), TextBox).Text)
'attach the fields to the inventory context
' note: Id autoincrements and doesn't need to be set manually
InsertInventoryItem(addInventory)
'need to call a gridview refresh here
GridView1.DataBind()
ElseIf e.CommandName = "Delete" Then
**addInventory.Id = Convert.ToInt32(DirectCast(cells(3).FindControl("lblEditId"), Label).Text)**
DeleteInventoryItem(Convert.ToInt32(addInventory.Id))
GridView1.DataBind()
End If
End Sub
I am getting the following error on the deleting routine where the **, why? The insert function works the same way and works properly.
Object reference not set to an instance of an object.
I think the problem is you're looking the Label lblEditId in Footer controls:
Dim cells = GridView1.FooterRow.Cells
...
addInventory.Id = Convert.ToInt32(DirectCast(cells(3).FindControl("lblEditId"), Label).Text)
Try this instead:
Update your delete linkbutton to (add the ID to the CommandArgument):
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Delete" CommandArgument='<%#Eval("Id")%>' Text="Delete"></asp:LinkButton>
Then, replace your ** code with this:
Note: Based on the code you provided, it seem like the lblEditId is in column 2 hence the Cell(1) - zero based index, instead of Cell(3).
addInventory.Id = Convert.ToInt32(DirectCast(GridView1.Rows(e.CommandArgument).Cells(1).FindControl("lblEditId"), Label).Text)
Related
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.
My page has a GridView for managing Factory Plants. I'm able to successfully edit the data in the Grid by clicking the edit link and then saving my changes upon clicking the update link. I want the ID column of the Grid to be hidden from the user, so I added the Visible Property to the Plant_ID column of the Grid and set it to false, the column is hidden, but I get an error: "Input string was not in a correct format" upon hitting the update link.
This is my Grid and SQL data Source:
<asp:GridView ID="GridPlants" runat="server" DataKeyNames="Plant_ID" AllowPaging="True" PageSize="7"
AllowSorting="True" AutoGenerateColumns="False" AutoGenerateEditButton="True"
BorderWidth="2px" CellPadding="2" CssClass="datatable" GridLines="None"
ShowFooter="True" SortedAscendingCellStyle-CssClass="sortasc" OnSorting="gvPlant_Sorting"
SortedAscendingHeaderStyle-CssClass="sortasc"
SortedDescendingCellStyle-CssClass="sortdesc"
SortedDescendingHeaderStyle-CssClass="sortdesc"
OnRowCancelingEdit="GridPlants_RowCancelingEdit"
OnRowEditing="GridPlants_RowEditing" OnRowUpdating="GridPlants_RowUpdating" OnPageIndexChanging="gvPlants_PageIndexChanging"
>
<EditRowStyle />
<PagerStyle CssClass="pager-row" />
<RowStyle CssClass="row" />
<Columns>
<asp:BoundField DataField="Plant_ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="Plant_ID" Visible="false" />
<asp:TemplateField HeaderText="Plant Name" SortExpression="Plant_Name">
<EditItemTemplate>
<asp:TextBox ID="Txtplant" runat="server" Text='<%# Bind("Plant_Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Plant_Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Plant Code" SortExpression="Plant_code">
<EditItemTemplate>
<asp:TextBox ID="Txtcode" runat="server" Text='<%# Bind("Plant_code") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Plant_code") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address" SortExpression="Address">
<EditItemTemplate>
<asp:TextBox ID="Txtaddress" runat="server" Text='<%# Bind("Address") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Address") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City" SortExpression="City">
<EditItemTemplate>
<asp:TextBox ID="Txtcity" runat="server" Text='<%# Bind("City") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("City") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="State" SortExpression="State">
<EditItemTemplate>
<asp:TextBox ID="Txtstate" runat="server" Text='<%# Bind("State") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("State") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Zip" SortExpression="Zip">
<EditItemTemplate>
<asp:TextBox ID="Txtzip" runat="server" Text='<%# Bind("Zip") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label6" runat="server" Text='<%# Bind("Zip") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Plant Email" SortExpression="Plant_Email">
<EditItemTemplate>
<asp:TextBox ID="Txtemail" runat="server" Text='<%# Bind("Plant_Email") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label7" runat="server" Text='<%# Bind("Plant_Email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Active" SortExpression="Active">
<EditItemTemplate>
<asp:CheckBox ID="Chkactive" runat="server" Checked='<%# Bind("Active") %>'
Enabled="false" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" Checked='<%# Bind("Active") %>'
Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="UpdateBy" HeaderText="Update By"
ReadOnly="True" SortExpression="UpdateBy" />
<asp:BoundField DataField="UpdateDate" HeaderText="Update Date" ReadOnly="True"
SortExpression="UpdateDate" />
</Columns>
<%-- <PagerSettings FirstPageText="«" LastPageText="»" Mode="NumericFirstLast"
PageButtonCount="7" />--%>
<SortedAscendingCellStyle CssClass="sortasc" />
<SortedAscendingHeaderStyle CssClass="sortasc" />
<SortedDescendingCellStyle CssClass="sortdesc" />
<SortedDescendingHeaderStyle CssClass="sortdesc" />
</asp:GridView>
<asp:SqlDataSource ID="PlantDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:ShipmentNotification %>"
SelectCommand="select Plant_ID, Plant_Name, Plant_code, Address, City, State, Zip, Plant_Email, Active, UpdateDate, UpdateBy from Plant order by plant_code">
</asp:SqlDataSource>
This is my Update function:
Protected Sub GridPlants_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridPlants.RowUpdating
Dim Editrow As GridViewRow = GridPlants.Rows(e.RowIndex)
Dim PlantId As String = GridPlants.DataKeys(e.RowIndex)("Plant_ID")
Dim textplant As TextBox = Editrow.FindControl("txtplant")
Dim textcode As TextBox = Editrow.FindControl("txtcode")
Dim checkbox As CheckBox = Editrow.FindControl("chkactive")
Dim address As TextBox = Editrow.FindControl("txtaddress")
Dim city As TextBox = Editrow.FindControl("txtcity")
Dim state As TextBox = Editrow.FindControl("txtstate")
Dim zip As TextBox = Editrow.FindControl("txtzip")
Dim email As TextBox = Editrow.FindControl("txtemail")
'I get an error on the following line:
DL.AddUpdatePlants("Admin", "Edit", Editrow.Cells(1).Text, textplant.Text, textcode.Text, address.Text, city.Text, state.Text, zip.Text, email.Text, checkbox.Checked)
'CType(Editrow.Cells(2).Controls(0), TextBox)).
GridPlants.EditIndex = -1
BindData()
End Sub
...Snippet of the stored procedure:
Dim myCommand As New SqlCommand("SavePlantDetails", myConnection)
myCommand.CommandType = CommandType.StoredProcedure
myCommand.Parameters.AddWithValue("#editType", addupdate)
myCommand.Parameters.AddWithValue("#Plant_ID", plant_id)
myCommand.Parameters.AddWithValue("#Plant_Name", name)
myCommand.Parameters.AddWithValue("#Plant_code", code)
myCommand.Parameters.AddWithValue("#address", address)
myCommand.Parameters.AddWithValue("#city", city)
myCommand.Parameters.AddWithValue("#state", state)
myCommand.Parameters.AddWithValue("#zip", zip)
myCommand.Parameters.AddWithValue("#email", email)
myCommand.Parameters.AddWithValue("#username", username)
myCommand.Parameters.AddWithValue("#Active", active)
myCommand.ExecuteNonQuery()
myConnection.Close()
...I'm wondering if by hiding the Plant_ID field, is that throwing off how I have my columns arranged? Could I get some help with this issue please? I only get the error after added the Visible property to the Plant_ID column and setting it to True. Thanks in advance.
Your value for Editrow.Cells(1).Text may not be coming up with visible false.
You can use the DataKeyNames property of the grid view to retrive this value.
set it as follows:
<asp:GridView ID="GridPlants" runat="server" DataKeyNames="Plant_ID" /> // rest of gridview markup
retrieve it as follows:
Dim PlantId as String = GridPlants.DataKeys(e.RowIndex)("Plant_ID")
and use this in your update function.
The Concept:
Editrow.Cells(1).Text
or in General:
rows.Cells(index).Text can ONLY be used to read data from a <asp:BoundField> field.
If you have TemplateFields as in <ItemTemplate> and <EditItemTemplate>, You must use the FindControl() method.
Here you have set AutoGenerateEditButton="true", thus your first Column ( Cell Zero obviously ) will contain the edit buttons actually. Starting with 2nd Column ( Cell 1) will be your Fields as you defined in your GridView Markup.
CASE I::
When you have set Visible="true" for your first <asp:BoundField> field, then Cells(1).Text actually refers to the Text inside Your Bound Field which is correct.
CASE II::
However, when you set Visible="false" for your first <asp:BoundField> field, then Cells(1).Text NO more refers to the first BoundField, but actually it's the next TemplateField: Plant_Name. The Data/Text in case of <asp:TemplateField> Column isn't inside the Cells but inside the Controls placed in these TemplateFields. This is the reason you get an error.
I have a gridview that has a item template and an edit template. The problem is, whenever I click the edit button, the edit templates don't show up.
Here is my page code:
<asp:GridView
ID="RoutesGridView"
runat="server"
CssClass="table table-striped table-hover"
GridLines="None"
AutoGenerateColumns="False"
DataKeyNames="RouteId,LocationId,ConcurrencyId"
AllowPaging="true"
EmptyDataText="No Information Retrieved">
<Columns>
<asp:TemplateField Visible="false">
<EditItemTemplate>
<asp:Label id="RouteIdLB" runat="server" Text='<%# Bind("RouteId") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label id="RouteIdLB" runat="server" Text='<%# Bind("RouteId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<EditItemTemplate>
<asp:TextBox ID="NameTB" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="NameLB" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description" SortExpression="Description" >
<EditItemTemplate>
<asp:TextBox ID="DescriptionTB" runat="server" Text='<%# Bind("Description") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="DescriptionLB" runat="server" Text='<%# Bind("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Time Zone" SortExpression="TimeZoneCode">
<EditItemTemplate>
<asp:DropDownList ID="TimeZoneDDL" runat="server" DataSource="<%# GetTimeZones() %>" AppendDataBoundItems="true" DataTextField="TimeZoneCode" DataValueField="TimeZoneId" SelectedValue='<%# Bind("TimeZoneId") %>'>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("TimeZoneCode") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Is Active" SortExpression="IsActive" HeaderStyle-CssClass="textCenterAlign" ItemStyle-CssClass="textCenterAlign">
<EditItemTemplate>
<asp:CheckBox ID="IsActiveCB" runat="server" Checked='<%# Bind("IsActive") %>' />
</EditItemTemplate>
<ItemTemplate>
<%# IIf(Eval("IsActive").Equals(True), "<i class='icon-ok'></i>", " ")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Is Deleted" SortExpression="IsDeleted" HeaderStyle-CssClass="textCenterAlign" ItemStyle-CssClass="textCenterAlign">
<EditItemTemplate>
<asp:CheckBox ID="IsDeletedCB" runat="server" Checked='<%# Bind("IsDeleted") %>' Enabled="False" />
</EditItemTemplate>
<ItemTemplate>
<%# IIf(Eval("IsDeleted").Equals(True), "<i class='icon-ok'></i>", " ")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Actions" ItemStyle-CssClass="actions">
<EditItemTemplate>
<asp:LinkButton ID="SaveButton" runat="server" CssClass="btn btn-mini btn-primary hiddenButton" CommandName="Update" Visible="True" Enabled="True" ToolTip="Save pending changes" CommandArgument='<%# CType(Container, GridViewRow).RowIndex %>'><i class="icon-ok icon-white"></i>Save</asp:LinkButton>
<asp:LinkButton ID="CancelButton" runat="server" CssClass="btn btn-mini btn-danger hiddenButton" CommandName="Cancel" Visible="True" Enabled="True" ToolTip="Cancel pending changes" CommandArgument='<%# CType(Container, GridViewRow).RowIndex %>'><i class="icon-ban-circle icon-white"></i>Cancel</asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="EditButton" runat="server" CssClass="btn btn-mini btn-primary hiddenButton" CommandName="Edit" Visible="True" Enabled="True" ToolTip="Edit this entry" CommandArgument='<%# CType(Container, GridViewRow).RowIndex %>'><i class="icon-edit icon-white"></i>Edit</asp:LinkButton>
<asp:LinkButton ID="DeleteButton" runat="server" CssClass="btn btn-mini btn-danger hiddenButton" CommandName="Delete" Visible="True" Enabled="True" ToolTip="Delete this entry" CommandArgument='<%# CType(Container, GridViewRow).RowIndex %>' OnClientClick='return confirm("Are you certain that you want to delete this entry?");'><i class="icon-trash icon-white"></i>Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
VB code behind:
Protected Sub RoutesGridView_RowEditing(ByVal sender As System.Object, ByVal e As GridViewEditEventArgs) Handles RoutesGridView.RowEditing
Dim gv As GridView = CType(sender, GridView)
Dim row As GridViewRow = gv.Rows(e.NewEditIndex)
Dim RouteId As Integer = CInt(CType(row.FindControl("RouteIdLB"), Label).Text)
_Route = RouteManager.GetItem(RouteId, _dftIdentity)
gv.EditIndex = e.NewEditIndex
RoutesGridView_DataBind()
End Sub
Protected Sub RoutesGridView_RowCancelingEdit(ByVal sender As System.Object, ByVal e As GridViewCancelEditEventArgs) Handles RoutesGridView.RowCancelingEdit
_Route = Nothing
RoutesGridView.EditIndex = -1
RoutesGridView_DataBind()
End Sub
Protected Sub RoutesGridView_RowUpdating(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles RoutesGridView.RowUpdating
Try
Dim gv As GridView = CType(sender, GridView)
Dim row As GridViewRow = gv.Rows(e.RowIndex)
With _Route
.Name = CType(row.FindControl("NameTB"), TextBox).Text
.TimeZoneId = CType(row.FindControl("TimeZoneDDL"), DropDownList).SelectedValue
.IsActive = CType(row.FindControl("IsActiveCB"), CheckBox).Checked
End With
RouteManager.Update(_Route, _dftIdentity)
_Route = Nothing
gv.EditIndex = -1
RoutesGridView_DataBind()
Catch ex As Exception
ProcessException(ex)
End Try
End Sub
You need to change the Grid edit form property from auto
to template
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
have a gridview with template fields, one column contains a dropdownlist that should be populated with a sql statement. I have created the grid dynamically and called the rowdatabound in order to access the dropdownlist but I keep recieving the error: Object reference not set to an instance of an object. Anyone have any ideas?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:CommandField EditText="Add" ShowEditButton="True" />
<asp:TemplateField>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<EditItemTemplate>
<asp:DropDownList ID="DropDownList2" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<EditItemTemplate>
<asp:Label ID="Label6" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label7" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This is the code for the creation of the GridView Dynamically, this is done in the page_load event:
If Not Page.IsPostBack Then
Dim CommittedTable As New DataTable("Committed")
CommittedTable.Columns.Add("Date Posted", GetType(Date))
CommittedTable.Columns.Add("Vendor", GetType(String))
CommittedTable.Columns.Add("Expense Description", GetType(String))
CommittedTable.Columns.Add("Ledger", GetType(String))
CommittedTable.Columns.Add("Amount", GetType(String))
CommittedTable.Columns.Add("Initials", GetType(String))
For i As Integer = 0 To GridView1.Rows.Count
Dim tableRow As DataRow = CommittedTable.NewRow()
tableRow("Date Posted") = Date.Today
tableRow("Vendor") = ""
tableRow("Expense Description") = ""
tableRow("Ledger") = ""
tableRow("Amount") = ""
tableRow("Initials") = ""
CommittedTable.Rows.Add(tableRow)
Next
Session("CommsTable") = CommittedTable
BindDataComm()
End If
Lastly this is the RowDataBound event handler code:
Dim ddl As DropDownList = DirectCast(e.Row.FindControl("DropDownList1"), DropDownList)
If ddl Is Nothing Then
result = dbConnect(dbType.SqlServer, ConfigurationManager.AppSettings("SQLServerConnection"))
If result = "Successful" Then
dt = FillDataTable(dbType.SqlServer, "SELECT V_VendorNo + ' | ' + V_VendorName FROM VendorTbl")
ddl.DataSource = dt 'it errors out here'
ddl.DataTextField = "V_VendorNo"
ddl.DataValueField = "V_VendorName"
ddl.DataBind()
End If
End If
Are you checking the RowType for Datarow before binding the Data in RowDatabound event if not Please check it....