Edit template not displaying - asp.net

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

Related

DropDown binding in gridview

I have this code:
<asp:TemplateField HeaderText="Gestisci IP" SortExpression="GestisciIp">
<EditItemTemplate>
<asp:DropDownList ID="ddlGestisciIP" runat="server" AppendDataBoundItems="true"
DataSourceID="SqlDataSource3" DataTextField="GestisciIP"
DataValueField="GestisciIP" SelectedValue='<%# Bind("GestisciIP") %>'>
<asp:ListItem Text="True" Value="True" />
<asp:ListItem Text="False" Value="False" />
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("GestisciIp") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
The datasource contain the value of a field selected on the current user (user id) and it can be True or False.
My problem is that I want the dropdown to always shows the 2 options True and False, but it should also have the selected value got from the datasource.
If I remove the 2 lines
<asp:ListItem Text="True" Value="True" />
<asp:ListItem Text="False" Value="False" />
it only shows the value got from the db, if I leave these lines it shows 3 values: the one got from the db and True, False added by this code.
So, how can I do this? I hope I was clear enough, thanks
IT'S DONE!
Thank you again
ASPX
<asp:TemplateField HeaderText="Gestisci IP" SortExpression="GestisciIp">
<EditItemTemplate>
<asp:DropDownList ID="ddlGestisciIP" runat="server">
</asp:DropDownList>
<asp:ListItem Text="True" Value="True" />
<asp:ListItem Text="False" Value="False" />
</asp:DropDownList>--%>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("GestisciIp") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
CODE BEHIND
Private Sub GridView2_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView2.RowCommand
If e.CommandName = "Edit" Then
Dim gvRow As GridViewRow = DirectCast(DirectCast(e.CommandSource, LinkButton).NamingContainer, GridViewRow)
Dim lbl As Label = DirectCast(gvRow.FindControl("Label2"), Label)
ViewState("LabelValue") = lbl.Text
End If
End Sub
Private Sub GridView2_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView2.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow AndAlso GridView2.EditIndex = e.Row.RowIndex Then
Dim ddlGestisciIP As DropDownList = DirectCast(e.Row.FindControl("ddlGestisciIP"), DropDownList)
Dim LblddlGestisciIP As Label = DirectCast(e.Row.FindControl("LblddlGestisciIP"), Label)
ddlGestisciIP.Items.Add(New ListItem("True", "1"))
ddlGestisciIP.Items.Add(New ListItem("False", "0"))
If Convert.ToString(ViewState("LabelValue")) <> "" Then
ddlGestisciIP.SelectedValue = ddlGestisciIP.Items.FindByText(Convert.ToString(ViewState("LabelValue"))).Value
End If
End If
End Sub
Private Sub GridView2_RowUpdating(sender As Object, e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView2.RowUpdating
Dim ddlGestisciIP As DropDownList = DirectCast(GridView2.Rows(GridView2.EditIndex).FindControl("ddlGestisciIP"), DropDownList)
SqlDataSourceUtenti.UpdateCommand = "UPDATE [Utenti] SET [RfProfilo] = #RfProfilo, [Nome] = #Nome, [Cognome] = #Cognome, [Username] = #Username, [Password] = #Password, [Badge] = #Badge, [IpCorretto] = #IpCorretto, [GestisciIp] = " & ddlGestisciIP.SelectedValue & " WHERE [IdUtente] = #Original_IdUtente"
End Sub
try this,add Onrowdatabound event to your gridview and bind your dropdownlist in that event.
<asp:GridView ID="GridView2" runat="server" AllowPaging="True" CellPadding="4" DataSourceID="SqlDataSourceUtenti"
ForeColor="#333333" GridLines="None" AutoGenerateColumns="False"
DataKeyNames="IdUtente" BorderColor="#E1E1E1" BorderStyle="Solid"
BorderWidth="3px" OnRowDataBound="GridView2_RowDataBound" OnRowCommand="GridView2_RowCommand" OnRowUpdating="GridView2_RowUpdating" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="RfProfilo" HeaderText="RfProfilo"
SortExpression="RfProfilo" Visible="False" />
<asp:BoundField DataField="Nome" HeaderText="Nome" SortExpression="Nome" />
<asp:BoundField DataField="Cognome" HeaderText="Cognome"
SortExpression="Cognome" />
<asp:BoundField DataField="Username" HeaderText="Username"
SortExpression="Username" />
<asp:TemplateField HeaderText="Profilo" SortExpression="Profilo">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource2" DataTextField="Nome" DataValueField="idProfilo"
SelectedValue='<%# Bind("RfProfilo") %>'>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("NomeProfilo") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Password" SortExpression="Password">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Password") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# mascheraPassword(Eval("Password").ToString()) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Badge" HeaderText="Badge" SortExpression="Badge" />
<asp:TemplateField HeaderText="IP di origine" SortExpression="IpCorretto">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("IpCorretto") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblIpCorretto" maxlength="16" runat="server" Text='<%# limitaCaratteri(Eval("IpCorretto").ToString()) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Gestisci IP" SortExpression="GestisciIp">
<EditItemTemplate>
<asp:DropDownList ID="ddlGestisciIP" runat="server">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("GestisciIp") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True"
CommandName="Update" Text="Aggiorna" ForeColor="White"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Annulla" ForeColor="White"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Edit" Text="Modifica"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="Delete" Text="Elimina"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
in code behind
Protected Sub GridView2_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
If e.CommandName = "Edit" Then
Dim gvRow As GridViewRow = DirectCast(DirectCast(e.CommandSource, LinkButton).NamingContainer, GridViewRow)
Dim lbl As Label = DirectCast(gvRow.FindControl("Label2"), Label)
ViewState("LabelValue") = lbl.Text
End If
End Sub
Private Sub GridView2_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView2.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow AndAlso GridView2.EditIndex = e.Row.RowIndex Then
Dim ddlGestisciIP As DropDownList = DirectCast(e.Row.FindControl("ddlGestisciIP"), DropDownList)
ddlGestisciIP.Items.Add(New ListItem("True", "1"))
ddlGestisciIP.Items.Add(New ListItem("False", "0"))
If Convert.ToString(ViewState("LabelValue")) <> "" Then
ddlGestisciIP.SelectedValue = ddlGestisciIP.Items.FindByText(Convert.ToString(ViewState("LabelValue"))).Value
End If
End If
End Sub
First ,With the use of RowCommand Event of the Grid View , Get the value of the Edited Label into the ViewState,then Use viewstate and Handle your RowDataBound
and to upadate your data you can use roeupdate event,like follows
protected void Gridview2_RowUpdating(Object sender, GridViewUpdateEventArgs e)
{
//add code for updating values in database
}
If i understood correct, you only want the values TRUE and FALSE, so, you don't need a datasource to do this...
Remove this properties DataSourceID, DataTextField, DataValueField and SelectedValue...
Try it please.

Input String not in correct format error, only when ID column Visible Property is set to false

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.

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

getting datarow vales in gridview error

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)

GridView Error: Object reference not set to an instance of an object

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....

Resources