Adding Dropdown List Item to ASP GridView - asp.net

I want to be able to take a selected item from a dropdown list, hit a button, and have that item added to a GridView to be viewed by the user. Right now, when I hit the + button, the grid displays, but the cells are blank. Any suggestions?
ASP code:
<tr>
<td valign="top" colspan="2">
<b>Agents Visited</b><br />
<asp:DropDownList SelectionMode="Multiple" runat="server" ID="agentsDropdown" Name="agentsDropdown" width="425"></asp:DropDownList>
</td>
<td valign="top">
<br />
<asp:Button id="agentButton" name="agentButton" runat="server" Text="+" OnClick="AddAgent" CssClass="buttonstyle" onmouseover="shade(this);" onmouseout="unshade(this);" />
</td>
</tr>
<tr>
<asp:GridView ID="agentGridView" Visible="False" AllowSorting="False" AllowPaging="False" Runat="server" AutoGenerateColumns="False" PageSize="20" >
<Columns>
<asp:TemplateField HeaderText="Agent">
<ItemTemplate>
<asp:Label ID="agentName" runat="server" Text=''></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Value">
<ItemTemplate>
<asp:Label ID="agentValue" runat="server" Text=''></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
</tr>
Initial GridView bind:
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack
agentGridView.DataSource = Nothing
agentGridView.Databind()
End If
End Sub
Additional code behind:
Protected Sub AddAgent(sender As Object, e As EventArgs)
If agentsDropdown.SelectedIndex > 0 Then
Dim dt As New DataTable
dt.Columns.Add("agentName")
dt.Columns.Add("agentValue")
Dim row1 As DataRow = dt.NewRow
row1.Item("agentName") = agentsDropdown.SelectedItem.Text.ToString()
row1.Item("agentValue") = agentsDropdown.SelectedValue.ToString()
dt.Rows.Add(row1)
agentGridView.DataSource = dt
agentGridView.DataBind()
agentsDropdown.SelectedIndex = 0
Dim agentRowsCount as Integer = agentGridView.Rows.Count
If agentRowsCount > 0
agentGridView.Visible = True
End If
End If
End Sub

This should work for you now. Change your GridView to the following:
<asp:GridView ID="agentGridView" Visible="False" AllowSorting="False" AllowPaging="False" Runat="server" AutoGenerateColumns="False" PageSize="20" >
<Columns>
<asp:BoundField DataField="agentName" HeaderText="Agent Name" ItemStyle-Width="30" />
<asp:BoundField DataField="agentValue" HeaderText="Agent Value" ItemStyle-Width="30" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>

See if this will work for you. I am more c# however this looked like it worked:
Public Class WebForm1
Inherits System.Web.UI.Page
Dim dt = Nothing
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Session("Agents") Is Nothing) Then
dt = New DataTable
Else
dt = Session("Agents")
End If
If Not Page.IsPostBack Then
agentGridView.DataSource = Nothing
agentGridView.DataBind()
End If
End Sub
Protected Sub AddAgent(sender As Object, e As EventArgs) Handles agentsDropdown.SelectedIndexChanged
If agentsDropdown.SelectedIndex > 0 Then
If (Session("Agents") Is Nothing) Then
dt = New DataTable()
dt.Columns.Add("agentName")
dt.Columns.Add("agentValue")
End If
Dim row1 As DataRow = dt.NewRow
row1.Item("agentName") = agentsDropdown.SelectedItem.Text.ToString()
row1.Item("agentValue") = agentsDropdown.SelectedValue.ToString()
dt.Rows.Add(row1)
Session("Agents") = dt
agentGridView.DataSource = dt
agentGridView.DataBind()
agentsDropdown.SelectedIndex = 0
Dim agentRowsCount As Integer = agentGridView.Rows.Count
If agentRowsCount > 0 Then
agentGridView.Visible = True
End If
End If
End Sub
End Class

Related

Fill GridView based on DropDownList.SelectedValue and Button Click

struggling since morning. the scenario is as follow:
I have a ASP.NET web page having
two dropdownlist
two buttons
One GridView
Wants to fill gridview based on dropdownlist selected value
here is the .aspx code
<%# Page Title="" Language="VB" MasterPageFile="~/Admin/ADMIN.master" AutoEventWireup="false" CodeFile="EditSTUdetail.aspx.vb" Inherits="Admin_EditSTUdetail" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<style type="text/css">
.auto-style1
{
height: 42px;
}
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<div align="center">
<fieldset>
<legend style="font-size: 16px;">SEARCH / EDIT / DELETE STUDENT RECORDS
</legend>
<div style="overflow: auto">
<div>
<asp:Label ID="lblMsg" runat="server" CssClass="lblresponse" />
<table style="margin: 3px auto 1px auto; height: 72px;">
<tr>
<td style="text-align: right;" class="auto-style2">Select Session/सत्र का चयन करें :
</td>
<td class="auto-style3">
<asp:DropDownList ID="ddlSession" runat="server" AppendDataBoundItems="True" Width="236px" Height="28px">
<asp:ListItem Text="--Select Session--" Value=""></asp:ListItem>
<asp:ListItem Text="" Value=""></asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*" ControlToValidate="ddlSession" ForeColor="#990000"></asp:RequiredFieldValidator></td>
</tr>
<tr>
<td style="text-align: right;" class="auto-style1">Select Course /कक्षा का चयन करें :
</td>
<td>
<asp:DropDownList ID="ddlCourse" runat="server" AppendDataBoundItems="true" Width="236px" Height="28px">
<asp:ListItem Text="--Select Course--" Value=""></asp:ListItem>
<asp:ListItem Text="" Value=""></asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="*" ControlToValidate="ddlCourse" ForeColor="#990000"></asp:RequiredFieldValidator></td>
</tr>
<tr>
<td class="auto-style1"></td>
<td class="auto-style1">
<asp:Button ID="btnSearch" runat="server" Text="SEARCH" CssClass="button" OnClick="btnSearch_Click" Height="34px" Width="77px" /></td>
<td colspan="2" class="auto-style1">
<asp:Button ID="btnRefresh" runat="server" Text="REFRESH" CssClass="button" OnClick="btnRefresh_Click" Height="34px" Width="77px" /></td>
</tr>
</table>
</div>
</div>
<asp:GridView ID="GVdata" runat="server" Width="674px" CaptionAlign="Top"
AutoGenerateColumns="False" Height="100px" BackColor="White"
BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3"
CellSpacing="2" GridLines="Vertical"
EmptyDataText="There Are No Record Found" OnRowCancelingEdit="gvManageOrders_RowCancelingEdit"
OnRowDeleting="gvManageOrders_RowDeleting" OnRowEditing="gvManageOrders_RowEditing"
OnRowUpdating="gvManageOrders_RowUpdating">
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:TemplateField HeaderText="Sr. No." ItemStyle-Width="20">
<ItemTemplate>
<asp:Label ID="lblRowNumber" Text='<%# Container.DataItemIndex + 1 %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Edit/Remove" ShowDeleteButton="True"
ShowEditButton="True" DeleteText="Remove" />
<asp:TemplateField HeaderText="Student ID" Visible="True">
<ItemTemplate>
<asp:Label ID="studentID" runat="server" Text='<%# Bind("studentID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Student Name" Visible="True">
<ItemTemplate>
<asp:Label ID="Sname" runat="server" Text='<%# Bind("Sname")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Father's Name" Visible="True">
<ItemTemplate>
<asp:Label ID="Fname" runat="server" Text='<%# Bind("Fname")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataRowStyle BackColor="#eeeeee" BorderColor="Black"
BorderStyle="Solid" BorderWidth="1px" Font-Size="Large" ForeColor="#851010"
HorizontalAlign="Center" />
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="#851010" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#851010" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>
</fieldset>
</div>
</asp:Content>
and here is my vb code:
Imports System.Collections.Generic
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Globalization
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Net.Mail
Imports System.Data
Imports System.ComponentModel
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Partial Public Class Admin_EditSTUdetail
Inherits System.Web.UI.Page
Private myds As DataSet
Protected Sub LoadSession()
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("cmsDB").ConnectionString)
con.Open()
Dim com As New SqlCommand("select sessionID, session from tblcategories ORDER by session DESC", con)
Dim da As New SqlDataAdapter(com)
Dim ds As New DataSet()
da.Fill(ds)
ddlSession.DataTextField = ds.Tables(0).Columns("session").ToString()
' text field name of table dispalyed in dropdown
ddlSession.DataValueField = ds.Tables(0).Columns("sessionID").ToString()
' to retrive specific textfield name
ddlSession.DataSource = ds.Tables(0)
'assigning datasource to the dropdownlist
ddlSession.DataBind()
ddlSession.SelectedIndex = -1
'binding dropdownlist
End Sub
Protected Sub LoadCourse()
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("cmsDB").ConnectionString)
con.Open()
Dim com As New SqlCommand("SELECT DISTINCT course AS mycolumn FROM " _
& " tblsubjects where course is not null and " _
& "not course = '' order by mycolumn", con)
Dim da As New SqlDataAdapter(com)
Dim ds As New DataSet()
da.Fill(ds)
ddlCourse.DataTextField = ds.Tables(0).Columns("mycolumn").ToString()
' text field name of table dispalyed in dropdown
ddlCourse.DataValueField = ds.Tables(0).Columns("mycolumn").ToString()
' to retrive specific textfield name
ddlCourse.DataSource = ds.Tables(0)
'assigning datasource to the dropdownlist
ddlCourse.DataBind()
ddlCourse.SelectedIndex = -1
'binding dropdownlist
End Sub
Protected Sub fillgrid()
Dim cn As New SqlConnection(ConfigurationManager.ConnectionStrings("cmsDB").ConnectionString)
Dim cmd As New SqlCommand("SELECT StudentID,session,course,Sname,Fname FROM [tblstudetail] WHERE " _
& " [session] = '" + ddlSession.SelectedValue.ToString() + "' AND " _
& " [course] = '" + ddlCourse.SelectedValue.ToString() + "'", cn)
cn.Open()
Dim da As New SqlDataAdapter(cmd)
myds = New DataSet()
da.Fill(myds)
GVdata.DataSource = myds
GVdata.DataBind()
End Sub
Private Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
LoadSession()
LoadCourse()
fillgrid()
End If
End Sub
Protected Sub gvManageOrders_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs)
Throw New NotImplementedException
End Sub
Protected Sub gvManageOrders_RowDeleting(sender As Object, e As GridViewDeleteEventArgs)
Throw New NotImplementedException
End Sub
Protected Sub gvManageOrders_RowEditing(sender As Object, e As GridViewEditEventArgs)
Throw New NotImplementedException
End Sub
Protected Sub gvManageOrders_RowUpdating(sender As Object, e As GridViewUpdateEventArgs)
Throw New NotImplementedException
End Sub
Protected Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
If Not Page.IsPostBack Then
fillgrid()
End If
End Sub
Protected Sub btnRefresh_Click(sender As Object, e As EventArgs) Handles btnRefresh.Click
GVdata.DataSource = Nothing
End Sub
End Class
But it is not returning what i request.
Kindly HELP me out this....
PLease remove these lines ,
ddlSession.SelectedIndex = -1
ddlCourse.SelectedIndex = -1
from the end of the LoadCourse and LoadSession methods. These are resetting the dropdown values and causing issue.
The flow is messed up in your code. You are calling loadsession , loadcourses and fillgrid serially from the page load method. Think about it. When the code in fillgrid executes there is no selected value in the drop downs. Obviously no data is found and so the gridview is not visible.
The better way to handle is introduce two new methods like this,
Protected Sub ddlCourses_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ddlSession.SelectedIndexChanged
and
Protected Sub ddlAC3_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ddlCourse.SelectedIndexChanged
Inside these methods send out a call to fillgrid.
Also inside the fillgrid method first validate there is some value in both the ddlCourse and ddlSession dropdowns , then send out the database command.
First of all
ddlSession.SelectedValue.ToString()
become
ddlSession.SelectedValue
Then in Protected Sub btnSearch_Click remove
If Not Page.IsPostBack Then
Then
ddlCourse.SelectedIndex = -1
become
ddlCourse.ClearSelection();
Finally, are you sure there aren't NULL value in the database?

Multiple delete wont work (asp.net vb)

code sample aspx vb behind code:
Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
For Each row As GridViewRow In GridView1.Rows
Dim checkbox As CheckBox = CType(row.FindControl("chkdelete"), CheckBox)
If checkbox.Checked Then
Dim ID As Integer = Convert.ToInt32(GridView1.DataKeys(row.RowIndex).Value)
SqlDataSource1.DeleteParameters("ID").DefaultValue = ID.ToString()
SqlDataSource1.Delete()
End If
Next row
front code :
`
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkdelete" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="No"
SortExpression="ID"/>
<asp:BoundField DataField="Name" HeaderText="Name"
SortExpression="Name"/>
<asp:CommandField Headertext="Edit" ShowEditButton="True" />
<asp:CommandField Headertext="Delete" ShowDeleteButton="True" />
</Columns>
</asp:GridView>
<asp:Button ID="btnDelete" runat="server" Text="Delete" onclick="btnDelete_Click"/>`
my question is, why my multiple delete still wont work? whats wrong with my code? anyone pls help..
Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
For Each row As GridViewRow In GridView1.Rows
Dim checkbox As CheckBox = CType(row.FindControl("chkdelete"), CheckBox)
If checkbox.Checked Then
Dim ID As Integer = Convert.ToInt32(GridView1.DataKeys(row.RowIndex).Value)
Delete(ID)
End If
Next row
End Sub
Public Function Delete(ByRef ID as Integer)
' Your Connection Coding comes here
SqlDataSource1.DeleteParameters("ID").DefaultValue = ID.ToString()
SqlDataSource1.Delete()
End Function
Try This Way..!!

GridView Edit Button Requires 2 Clicks

When pressing edit button in gridview, edit template is displayed only after 2 clicks.
And another problem: Value of the field to edit is displayed in gridview initially, but not in edit template.
Asp code:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
AutoGenerateColumns="False" CellPadding="4" OnRowEditing="EditRow"
OnRowCancelingEdit="CancelEditRow" DataKeyNames="AREA" DataMember="DefaultView">
<Columns>
<asp:BoundField DataField="AREA" HeaderText="AREA" ReadOnly="True"
SortExpression="AREA" />
<asp:TemplateField HeaderText="LEADER_USER" SortExpression="LEADER_USER">
<ItemTemplate><%#Eval("leader_user")%></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtleaderuser" runat="server" Text='<%#Eval("leader_user")%>'/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="editButton" runat="server" CommandName="Edit"
ImageUrl="images/pencil1.png" Text="Edit" ToolTip="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="BtnUpdate" runat="server" CommandName="Update"
Text="Update" />
<asp:Button ID="BtnCancel" runat="server" CommandName="Cancel"
Text="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
vb code:
Protected Sub EditRow(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
GridView1.EditIndex = e.NewEditIndex
GridView1.DataSource = SqlDataSource1
'If Not IsPostBack Then
'GridView1.DataSourceID = SqlDataSource1.ID
'GridView1.DataBind()
'End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
SqlDataSource1.SelectCommand = "SQL"
SqlDataSource1.ConnectionString = "My conn string"
If Not IsPostBack Then
'GridView1.DataSourceID = SqlDataSource1.ID
GridView1.DataSource = SqlDataSource1
GridView1.DataBind()
End If
End Sub
I think you need to call DataBind to rebind the data source. You've commented it out, but it looks like you had it in a IsPostBack block, which would only execute on the initial page load.
Try:
Protected Sub EditRow(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
GridView1.EditIndex = e.NewEditIndex
GridView1.DataSource = SqlDataSource1
GridView1.DataBind()
End Sub

trying to total gridview in asp

i am trying to total the price and quantity of all the products added to the gridview and i can't seem to figure out why the total is not showing in the footer. the code that i have for the vb should multiply the quantity with the price and put it into the footer of the gridview. the gridview footer is visible so i know that's not the problem. any help would be appreciated.
asp:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="Cart" AllowSorting="True" BackColor="White"
BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3"
GridLines="Vertical" ShowFooter="True" AutoGenerateEditButton="True"
AutoGenerateDeleteButton="True" DataKeyNames="cartID">
<AlternatingRowStyle BackColor="Gainsboro" />
<Columns>
<asp:BoundField DataField="cartID" HeaderText="cartID" SortExpression="cartID"
InsertVisible="False" ReadOnly="True" Visible="False"></asp:BoundField>
<asp:BoundField DataField="cartNO" HeaderText="cartNO" SortExpression="cartNO"
Visible="False" />
<asp:BoundField DataField="productID" HeaderText="productID"
SortExpression="productID" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="productName" HeaderText="productName"
SortExpression="productName" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="price" HeaderText="price"
SortExpression="price" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="quantity" HeaderText="quantity"
SortExpression="quantity" />
<asp:TemplateField HeaderText="SubTotal" SortExpression="subTotal" >
<ItemTemplate>
<%# Eval("price") * Eval("quantity")%>
</ItemTemplate>
<%-- <FooterTemplate>
<asp:Label ID="sum" runat="server"/>
</FooterTemplate>--%>
</asp:TemplateField>
VB
Public Class MyCart
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strcartNO As String = ""
Dim cookieBack As HttpCookie
cookieBack = HttpContext.Current.Request.Cookies("cartNO")
strcartNO = cookieBack.Value
'sqldscartLine.selectCommand = "Select * from cartLine where cartNO = '" & strcartNO & "'"
GridView1.DataBind()
End Sub
Public Shared Sub DeleteMethod(ByVal original_OrderID As Integer, _
ByVal original_ProductID As Integer)
End Sub
Dim priceTotal As Decimal = 0
Dim quantityTotal As Integer = 0
Sub GridView1_RowDataBound(ByVal sender As Object, _
ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
' add the UnitPrice and QuantityTotal to the running total variables
priceTotal += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, _
"price"))
quantityTotal += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, _
"quantity"))
ElseIf e.Row.RowType = DataControlRowType.Footer Then
e.Row.Cells(2).Text = "Totals:"
' for the Footer, display the running totals
e.Row.Cells(3).Text = priceTotal.ToString("c")
e.Row.Cells(4).Text = quantityTotal.ToString("d")
e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Right
e.Row.Cells(4).HorizontalAlign = HorizontalAlign.Right
e.Row.Font.Bold = True
End If
End Sub
Not sure if anybody saw the comment, so will put it in an answer instead - This might help others out (if I'm correct..)
Your code has the following in
<%-- <FooterTemplate>
<asp:Label ID="sum" runat="server"/>
</FooterTemplate>--%>
The <%-- and --%> are comments, so your footer is being commented out.
Change it to
<FooterTemplate>
<asp:Label ID="sum" runat="server"/>
</FooterTemplate>
And it should display.
Databinding creates data rows. The footer isn't a data row, so the event RowDataBound is not called when it's created. Thus, your event handler GridView1_RowDataBound will never execute the code that generates the totals, since the expression
e.Row.RowType = DataControlRowType.Footer
... will never be true during any execution of that method.
Try handling the RowCreated event instead, like so:
Sub GridView1_RowCreated(ByVal sender As Object, _
ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.Footer Then
e.Row.Cells(2).Text = "Totals:"
' for the Footer, display the running totals
e.Row.Cells(3).Text = priceTotal.ToString("c")
e.Row.Cells(4).Text = quantityTotal.ToString("d")
e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Right
e.Row.Cells(4).HorizontalAlign = HorizontalAlign.Right
e.Row.Font.Bold = True
End If
End Sub

Gridview - Update event not fire

When I click the "Edit" button of the gridview, it will show "Update" and "Cancel" button. But when I click "Update" button, it will not fire any event "RowUpdating", RowUpdated", "RowCommand"... It reload the page and then gridview disappear.
The following is my asp code:
<asp:GridView ID="Gridview1" runat="server" EnableViewState="False"
AutoGenerateColumns = "False" Font-Names = "Arial"
Font-Size = "10pt" AlternatingRowStyle-BackColor = "#C2D69B"
AutoGenerateEditButton="false"
AllowPaging ="True"
PageSize = "20"
OnRowCommand="GridView1_RowCommand"
OnRowDataBound="GridView1_RowDataBound"
OnRowEditing="GridView1_RowEditing"
OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowUpdating="GridView1_RowUpdating"
OnPageIndexChanging="GridView1_PageIndexChanging">
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<Columns>
<asp:BoundField DataField = "Name&Post" HeaderText = "Name & Post" ReadOnly ="true" />
<asp:TemplateField HeaderText="Working<br>Time">
<ItemTemplate>
<asp:Label ID="lb1_rosterkey" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Col1_RosterKey")%>' Visible ="false" ></asp:Label>
<asp:DropDownList ID="ddl1_shifttype" runat ="server" Enabled ="false" DataSourceID="SqlDataSource2" DataTextField ="en_name" DataValueField ="shift_type_key"> </asp:DropDownList>
<MKB:TimeSelector ID="Col1_StartTime" runat="server" DisplaySeconds="False" ReadOnly="true" MinuteIncrement="1" AmPm="AM" BorderColor="Silver"
Date="" Hour="07" Minute="0" SelectedTimeFormat="Twelve"> </MKB:TimeSelector>
<MKB:TimeSelector ID="Col1_EndTime" runat="server" DisplaySeconds="False" ReadOnly="true" MinuteIncrement="1" AmPm="PM" BorderColor="Silver"
Date="" Hour="07" Minute="0" SelectedTimeFormat="Twelve"> </MKB:TimeSelector>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddl1_shifttype" runat ="server" DataSourceID="SqlDataSource2" DataTextField ="en_name" DataValueField ="shift_type_key"></asp:DropDownList>
<MKB:TimeSelector ID="Col1_StartTime" runat="server" DisplaySeconds="False" MinuteIncrement="1" AmPm="AM" BorderColor="Silver"
Date="" Hour="07" Minute="0" SelectedTimeFormat="Twelve"> </MKB:TimeSelector>
<MKB:TimeSelector ID="Col1_EndTime" runat="server" DisplaySeconds="False" MinuteIncrement="1" AmPm="PM" BorderColor="Silver"
Date="" Hour="07" Minute="0" SelectedTimeFormat="Twelve"> </MKB:TimeSelector>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Leave/<br>TOIL">
<ItemTemplate>
<asp:CheckBox
ID="cb1_VL" Enabled="false" Text="VL"
runat="server"
Checked=<%#DataBinder.Eval(Container.DataItem, "Col1_VL")%> />
<asp:CheckBox
ID="cb1_SL" Enabled="false" Text="SL"
runat="server"
Checked=<%#DataBinder.Eval(Container.DataItem, "Col1_SL")%> />
<asp:CheckBox
ID="cb1_ML" Enabled="false" Text="ML"
runat="server"
Checked=<%#DataBinder.Eval(Container.DataItem, "Col1_ML")%> />
<asp:CheckBox
ID="cb1_PH" Enabled="false" Text="PH"
runat="server"
Checked=<%#DataBinder.Eval(Container.DataItem, "Col1_PH")%> />
<asp:CheckBox
ID="cb1_APH" Enabled="false" Text="APH"
runat="server"
Checked=<%#DataBinder.Eval(Container.DataItem, "Col1_APH")%> />
<asp:CheckBox
ID="cb1_TOIL" Enabled="false" Text="TOIL"
runat="server"
Checked=<%#DataBinder.Eval(Container.DataItem, "Col1_TOIL")%> />
<br />
<%#DataBinder.Eval(Container.DataItem, "Col1_Others")%>
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox
ID="cb1_VL" Text="VL"
runat="server"
Checked=<%#DataBinder.Eval(Container.DataItem, "Col1_VL")%> />
<asp:CheckBox
ID="cb1_SL" Text="SL"
runat="server"
Checked=<%#DataBinder.Eval(Container.DataItem, "Col1_SL")%> />
<asp:CheckBox
ID="cb1_ML" Text="ML"
runat="server"
Checked=<%#DataBinder.Eval(Container.DataItem, "Col1_ML")%> />
<asp:CheckBox
ID="cb1_PH" Text="PH"
runat="server"
Checked=<%#DataBinder.Eval(Container.DataItem, "Col1_PH")%> />
<asp:CheckBox
ID="cb1_APH" Text="APH"
runat="server"
Checked=<%#DataBinder.Eval(Container.DataItem, "Col1_APH")%> />
<asp:CheckBox
ID="cb1_TOIL" Text="TOIL"
runat="server"
Checked=<%#DataBinder.Eval(Container.DataItem, "Col1_TOIL")%> />
<asp:TextBox ID="tb1_Others" runat="server" Width="50" Text='<%#DataBinder.Eval(Container.DataItem, "Col1_Others") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
......
The following is the VB code:
Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
'Set the edit index.
Gridview1.EditIndex = e.NewEditIndex
'Bind data to the GridView control.
BindData()
End Sub
Protected Sub GridView1_RowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
'Reset the edit index.
Gridview1.EditIndex = -1
'Bind data to the GridView control.
BindData()
End Sub
Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
'Retrieve the table from the session object.
Dim dt = CType(Session("dt"), DataTable)
'Update the values.
Dim row = Gridview1.Rows(e.RowIndex)
'Reset the edit index.
Gridview1.EditIndex = -1
'Bind data to the GridView control.
BindData()
End Sub
Private Sub BindData()
Dim StartDateStr As String
StartDateStr = Trim(Request.QueryString("sd"))
StartDateStr = Left(StartDateStr, 10)
'date should be best in ISO format, i.e. yyyy-mm-ddTHH:mm:ss[.mmm] as "Set Dateformat dmy" is not supported by DataSet object
'StartDateStr = Right(StartDateStr, 4) & "-" & Mid(StartDateStr, 4, 2) & "-" & Left(StartDateStr, 2) & " T00:00:00"
Dim StartDate As DateTime
Dim EndDate As DateTime
StartDate = Convert.ToDateTime(StartDateStr)
EndDate = Format(DateAdd(DateInterval.Day, 6, StartDate), "dd/MM/yyyy")
g_header1 = StartDate 'Monday
g_header2 = Format(DateAdd(DateInterval.Day, 1, StartDate), "dd/MM/yyyy")
g_header3 = Format(DateAdd(DateInterval.Day, 2, StartDate), "dd/MM/yyyy")
g_header4 = Format(DateAdd(DateInterval.Day, 3, StartDate), "dd/MM/yyyy")
g_header5 = Format(DateAdd(DateInterval.Day, 4, StartDate), "dd/MM/yyyy")
g_header6 = Format(DateAdd(DateInterval.Day, 5, StartDate), "dd/MM/yyyy")
g_header7 = EndDate 'Sunday
Gridview1.DataSource = Session("dt")
Gridview1.DataBind()
End Sub
Protected Sub GridView1_DataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles Gridview1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow AndAlso e.Row.RowState = DataControlRowState.Edit Then
'If e.Row.RowType = DataControlRowType.DataRow Then
Dim row = DirectCast(e.Row.DataItem, DataRowView).Row
Dim Col1_StartTime = DirectCast(e.Row.FindControl("Col1_StartTime"), MKB.TimePicker.TimeSelector)
'set the TimePicker's Value here according to the Time-Value in the DataRow'
End If
End Sub
Protected Sub Gridview1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles Gridview1.RowCommand
If e.CommandName = "Update" Then
'Reset the edit index.
Gridview1.EditIndex = -1
'Bind data to the GridView control.
BindData()
End If
End Sub
Use buttons in asp:TemplateField with proper CommandName and it will fire the corresponding events.
Example
<asp:TemplateField>
<ItemTemplate>
<asp:Button id="btnEdit" runat="server" commandname="Edit" text="Edit" />
<asp:Button id="btnDelete" runat="server" commandname="Delete" text="Delete" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button id="btnUpdate" runat="server" commandname="Update" text="Update" />
<asp:Button id="btnCancel" runat="server" commandname="Cancel" text="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
I solved my problem.
I need to set CausesValidation="false"
make enableviewstate=true in gridview
did you write this at page load, if not add this
if me.ispostback= false then
'grid fill statement
end if
I'm not sure where your save/cancel buttons are located but you may need to add a command name to them as specified on MSDN
ie. <asp:buttonfield buttontype="Link" commandname="Update" text="Update"/>
I never used separate rowupdate/rowedit commands but i do use the following:
in my grid columns list, i'm adding the commandfield and images (optional for the buttons)
<asp:CommandField HeaderText="Edit" ButtonType="Image" ShowCancelButton="true" ShowEditButton="True"
EditImageUrl="../images/esig.gif" CancelImageUrl="../images/btn_close.gif"
UpdateImageUrl="../images/icn_ok.gif" />
I don't see this in your code.
a sample of a grid-editing as below
In the code behind, you should be able to check for the RowDataBound event as per below (Grida is the name of the sample grid)
Protected Sub Grida_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles Grida.RowDataBound
'check for row in edit mode
If (e.Row.RowState = DataControlRowState.Edit) then
' create handles for the row being edited
Dim drv As System.Data.DataRowView = CType(e.Row.DataItem, System.Data.DataRowView)
' locate the dropdownbox (in my page)
Dim dllven As DropDownList = CType(e.Row.Cells(3).FindControl("DropDownVendor"), DropDownList)
' check what item was selected in this DDL when in editmode
Dim li As ListItem = dllven.Items.FindByText(drv("Vendor").ToString)
' set the selection upon return
li.Selected = True
end if
End Sub
works perfectly for me.

Resources