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?
Related
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
Public Function GridView_RowUpdating(sender As Object, _
e As GridViewUpdateEventArgs) As Integer
Dim ID As Integer = GridView1.DataKeys(e.RowIndex).Value
Return ID
End Function
I need the id(datakey) for edit data from myGridview on another page. How can I do it?
chk this code will help you....
<asp:GridView ID="grdViewTracking" runat="server" AllowPaging="True" AllowSorting="true"
OnSorting="grdViewTracking_Sorting" AutoGenerateColumns="False" BorderColor="#E7E7E7"
BorderStyle="Solid" BorderWidth="1px" OnPageIndexChanging="grdViewTracking_PageIndexChanging"
CellPadding="1" ForeColor="#666666" PageSize="10" Width="100%">
<Columns>
<asp:TemplateField HeaderText="#" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<table>
<tr style="background-color: White">
<td style="padding-left: 5px;">
<%#DataBinder.Eval(Container.DataItem, "Number")%>
</td>
</tr>
</table>
</ItemTemplate>
<ItemStyle Width="5%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Key" SortExpression="Key" ItemStyle-HorizontalAlign="Left">
<HeaderStyle HorizontalAlign="Left" CssClass="PaddingLeft5" />
<ItemTemplate>
<table>
<tr style="background-color: White">
<td style="padding-left: 5px">
***<asp:LinkButton ID="lnkkey" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Key")%>'></asp:LinkButton>***
<input type=hidden runat="server" id="hfid" value=' <%#DataBinder.Eval(Container.DataItem, "Appsettingid")%>' />
</td>
</tr>
</table>
</ItemTemplate>
<ItemStyle Width="15%" />
</asp:TemplateField>
below code to transfer control to second page i.e. edit page.....
protected void grdViewTracking_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
BusinessLogicPOS.AppSettingArgs ob = e.Row.DataItem as BusinessLogicPOS.AppSettingArgs;
LinkButton lnkkey = e.Row.FindControl("lnkkey") as LinkButton;
lnkkey.PostBackUrl = "AppSetting.aspx?AppSettingId=" + ob.AppSettingId.ToString();
}
Check reference:
example
The simplest way to do this will be like this.
At WebForm1 markup use either of these two methods
a. Use a asp:TemplateField
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="EditLink" runat="server"
NavigateUrl='<%# "~/WebForm2.aspx?id=" + Eval("ID") %>'
Text="Update" />
</ItemTemplate>
</asp:TemplateField>
b. Use a asp:HyperLinkField
<asp:HyperLinkField Text="Update"
DataNavigateUrlFields="ID"
DataNavigateUrlFormatString="~\WebForm2.aspx?id={0}"
HeaderText="Action" />
And at WebForm2 code-behind do this
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
If Request.QueryString("id") IsNot Nothing Then
Dim passedID As String = Request.QueryString("id")
'populate the fields using .FirstOrDefault
Else
'no id passed. cannot process
End If
End If
End Sub
This is my datalist:
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1"
RepeatLayout="Flow">
<ItemTemplate>
<asp:Label ID="IdLabel" runat="server" Text='<%# Eval("ID") %>' Visible="False" />
Titre:
<asp:Label ID="TitreLabel" runat="server" Text='<%# Eval("Titre") %>' />
<br />
Description:
<asp:Label ID="DescriptionLabel" runat="server"
Text='<%# Eval("Description") %>' />
<br />
<asp:Image ID="Image1" runat="server"
ImageUrl='<%# Eval("ID", "Handler.ashx?ID={0}") %>' Width="200" Height="200"/>
<br />
comments:
<asp:Label ID="commentsLabel" runat="server" Text='<%# Eval("comments") %>' />
<br />
Ajouter commentaire
<asp:button ID="btnAjouter" runat="server" OnCommand="Button_Command"
CommandName="add" Text="Ajouter" />
<asp:TextBox ID="TextBoxComments" runat="server"></asp:TextBox>
<br/>
<br/>
</ItemTemplate>
</asp:DataList>
This my aspx.vb button event:
Sub Button_Command(ByVal sender As Object, ByVal e As CommandEventArgs)
Dim connectionString As String = WebConfigurationManager.ConnectionStrings("BecsEtMuseauxSQL").ConnectionString
Dim con As SqlConnection = New SqlConnection(connectionString)
con.Open()
Dim cmd As New SqlCommand("updateComments", con)
cmd.CommandType = CommandType.StoredProcedure
//I try this ....
cmd.Parameters.Add("#id", SqlDbType.Int).Value = DataList1.FindControl("IdLabel").ToString()
cmd.Parameters.Add("#Comments", SqlDbType.NVarChar).Value = DataList1.FindControl("TextBoxComments").ToString()
cmd.ExecuteNonQuery()
End Sub
I get an error like this: "The object reference is not definied to an object instance"
How can I catch the value from the label IdLabel and TextBoxComments in this situation?
You should handle the DataList's ItemCommand instead of the Button's Command.
Then you can find your controls with e.Item.FindControl:
Private Sub DataList1_ItemCommand(source As Object, e As System.Web.UI.WebControls.DataListCommandEventArgs) _
Handles DataList1.ItemCommand
If e.CommandName = "add" Then
Dim IdLabel = DirectCast(e.Item.FindControl("IdLabel"), Label)
Dim TextBoxComments = DirectCast(e.Item.FindControl("TextBoxComments"), TextBox)
' ... '
End If
End Sub
on aspx, remove your redundant Command-handler:
<asp:button ID="btnAjouter" CommandName="add" Text="Ajouter" runat="server" />
If you want to use the Button's Click-Event instead, that's possible also.
Protected Sub btnAjouter_Click(sender As Object, e As EventArgs)
Dim container = DirectCast(DirectCast(sender, Control).NamingContainer, DataListItem)
Dim IdLabel = DirectCast(container.FindControl("IdLabel"), Label)
Dim TextBoxComments = DirectCast(container.FindControl("TextBoxComments"), TextBox)
' ... '
End Sub
on aspx, add the click-event handler to the button:
<asp:button ID="btnAjouter" OnClick="btnAjouter_Click" Text="Ajouter" runat="server" />
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.
I had a basicSearch page working perfectly with the keyword searching (highlighting the keyword on the search result page) but when I modified it to work with a querystring, it's displaying ALL the records with the keyword highlighted.
aspx page:
<form id="form1" runat="server">
<div id="mainContent">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<script type="text/javascript">
function updated() {
// close the popup
tb_remove();
// refresh the update panel so we can view the changes
$('#<%= me.btnRefreshResources.ClientID %>').click();
}
function pageLoad(sender, args) {
if (args.get_isPartialLoad()) {
// reapply the thick box stuff
tb_init('a.thickbox');
}
}
</script>
<asp:AccessDataSource ID="AccessDataSource" runat="server"
DataFile="~/Dir/search.mdb"
SelectCommand="SELECT * FROM [searches] ORDER BY [Title]"
FilterExpression="Title like '%{0}%' or LastName like '%{1}%' or FirstName like '%{2}%' or Description like '%{3}%' ">
<FilterParameters>
<asp:ControlParameter Name="Title" ControlID="txtSearch" PropertyName="Text" />
<asp:ControlParameter Name="LastName" ControlID="txtSearch" PropertyName="Text" />
<asp:ControlParameter Name="FirstName" ControlID="txtSearch" PropertyName="Text" />
<asp:ControlParameter Name="Description" ControlID="txtSearch" PropertyName="Text" />
</FilterParameters>
</asp:AccessDataSource>
<div id="basicSearch" align="left">
<b style="font-family: Arial, Helvetica, sans-serif; font-size: 18px">Enter a keyword: </b><asp:TextBox ID="txtSearch" runat="server" Width="300px" Font-Size="18px" />
<asp:Button ID="btnBasicSearch" Text="Search" Runat="Server"/>
<asp:Button ID="btnBasicClear" Text="Clear" Runat="Server"/><br /><br />
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="btnRefreshResources" runat="server" style="display:none" OnClick="Refresh_Click" />
<asp:GridView ID="gvResources" runat="server" DataSourceID="AccessDataSource" CssClass="datagrid" GridLines="None" AutoGenerateColumns="false" AllowSorting="True" PageSize="50" AllowPaging="True" Width="100%" OnPageIndexChanging="gvResources_PageIndexChanging"> <PagerSettings Position="TopAndBottom" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" />
<asp:TemplateField HeaderText="Type" HeaderStyle-HorizontalAlign="Right" SortExpression="Title">
<ItemTemplate>
<%# DisplayType(Eval("Book"))%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title" SortExpression="Title">
<ItemTemplate>
<asp:Label ID="lblTitle" Text='<%# HighlightText(Eval("Title").ToString()) %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name" SortExpression="LastName">
<ItemTemplate>
<asp:Label ID="lblLastName" Text='<%# HighlightText(Eval("LastName").ToString()) %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name" SortExpression="FirstName">
<ItemTemplate>
<asp:Label ID="lblFirstName" Text='<%# HighlightText(Eval("FirstName").ToString()) %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lblDescription" Text='<%# HighlightText(Eval("Description").ToString()) %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<a id="btnShowPopup" runat="server" class="thickbox" title='<%# Eval("ID", "Request Resource ID: {0}") %>' href='<%# Eval("ID", "RequestResource.aspx?ID={0}&TB_iframe=true&height=350&width=500&modal=true") %>'>Request This Item</a> </ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
Code behind:
Partial Class BasicSearch
Inherits System.Web.UI.Page
Dim SearchString As String = ""
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
SearchString = Request.QueryString("Keyword")
End Sub
Protected Sub Refresh_Click(ByVal sender As Object, ByVal args As EventArgs)
' update the grids contents
Me.gvResources.DataBind()
End Sub
Function HighlightText(ByVal InputTxt As String) As String
If SearchString = "" Then
Return InputTxt
Else
Dim ResultStr As Regex
ResultStr = New Regex(SearchString.Replace(" ", "|"), RegexOptions.IgnoreCase)
Return ResultStr.Replace(InputTxt, New MatchEvaluator(AddressOf ReplaceWords))
End If
End Function
Public Function ReplaceWords(ByVal m As Match) As String
Return "<span class=highlight>" + m.ToString + "</span>"
End Function
Protected Sub gvResources_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
gvResources.PageIndex = e.NewPageIndex
SearchString = txtSearch.Text
gvResources.DataBind()
End Sub
Protected Sub btnBasicSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnBasicSearch.Click
SearchString = txtSearch.Text
Response.Redirect("BasicSearch.aspx?Keyword=" & SearchString)
End Sub
Protected Sub btnBasicClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnBasicClear.Click
txtSearch.Text = ""
SearchString = ""
End Sub
Protected Function DisplayType(ByVal Book As Boolean) As String
If Book Then
Return "Book"
Else
Return "Other"
End If
End Function
End Class
Just a guess - what is the value of SearchString when the HighlightText function is executing? You are storing the querystring in a local page variable, which only exists while the page request is executing.
If HighlightText gets called without Page_Load being called (in the same request), SearchString will be empty.