NullReferenceException when assigning dataset as datasource of dropdownlist - asp.net

I want to assign datasource of a dropdownlist which is inside a gridview control. But when i am executing the following code i am getting NullReferenceException.
Protected Sub grvStudent_DataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Try
Dim Connection As SqlConnection = New SqlConnection(ConnectionString)
Dim Query As String = "select Course from Courses"
Dim Command As SqlCommand
Command = New SqlCommand(Query, Connection)
Dim Da As New SqlDataAdapter(Command)
Dim Ds As New DataSet()
Connection.Close()
Dim ddlCourse = DirectCast(e.Row.FindControl("ddlCourse"), DropDownList)
Da.Fill(Ds)
ddlCourse.DataSource = Ds //Exception is here
ddlCourse.DataTextField = "Course"
ddlCourse.DataValueField = "Id"
ddlCourse.DataBind()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End If
End Sub

You are closing the connection before filling the dataset and also you have not opened the connection so first open the connection then fill the dataset after that you can close the connection.
Protected Sub grvStudent_DataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Try
Dim Connection As SqlConnection = New SqlConnection(ConnectionString)
Dim Query As String = "select Course from Courses"
Dim Command As SqlCommand
Command = New SqlCommand(Query, Connection)
Dim Da As New SqlDataAdapter(Command)
Dim Ds As New DataSet()
Connection.Open()
Dim ddlCourse = DirectCast(e.Row.FindControl("ddlCourse"), DropDownList)
Da.Fill(Ds)
ddlCourse.DataSource = Ds //Exception is here
ddlCourse.DataTextField = "Course"
ddlCourse.DataValueField = "Id"
ddlCourse.DataBind()
Catch ex As Exception
MsgBox(ex.ToString)
Finally
Connection.Close()
End Try
End If
End Sub
Edit :
Add this line and run
If (ds.Tables.Count > 0) Then
//your binding code....
Else
MsgBox(ex.ToString)
End If
For reference
Link

Make sure your drop down is in the ItemTemplate section of the grid in your HTML code, you may have it in the edit section only ..
<asp:TemplateField HeaderText="Course">
<EditItemTemplate>
<asp:DropDownList ID="ddlCourse" runat="server">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddlCourse" runat="server">
</asp:DropDownList>
<asp:Label ID="lblCourse" runat="server" />
</ItemTemplate>
</asp:TemplateField>

Related

How to filter data/conect on a grid view

I am making an ordering website as part of an assignment. A doctor logs in and sees all the orders put forward by his patients. When the doctor clicks some check boxes and clicks the button - the boxes that are checked update the orders (rows) column (approve) to approved. The unchecked boxes update the approve column to disapproved - this all works and updates...
however the grid does not disappear after this - the doctor can keep updating the orders and changing them but I want only the new orders that have not been checked/unchecked to appear. - I dont know how to apply this to my vb code.
I dont want the orders to delete from the database order table - just present the new orders to the doctor that he has not yet checked/unchecked.
my gird:
<asp:GridView ID="GridViewdoc" runat="server" AutoGenerateColumns="False" DataKeyNames="OrderId">
<Columns>
<asp:BoundField DataField="OrderID" HeaderText="Order Id" />
<asp:BoundField DataField="DoctorId" HeaderText="Doctor Id" />
<asp:BoundField DataField="Forename" HeaderText="Forename" />
<asp:BoundField DataField="Surname" HeaderText="Surname" />
<asp:BoundField DataField="MedicineId" HeaderText="Medicine Id" />
<asp:BoundField DataField="MedicineName" HeaderText="Medicine Name" />
<asp:BoundField DataField="pharmname" HeaderText="Pharmacy Name" />
<asp:BoundField DataField="Dateordered" HeaderText="Date Ordered" />
<asp:TemplateField HeaderText="Approve Status">
<ItemTemplate>
<asp:CheckBox ID="ApproveBox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
my code behind gid:
Imports System.Data.SqlClient
Imports System.Data
Partial Class Pages_docorders
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Dim conn As New System.Data.SqlClient.SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\surgerydb.mdf;Integrated Security=True;Connect Timeout=30")
Dim cmd3string As String = " Select * From docgridview WHERE DoctorId = " & Session("DoctorId")
Dim dt As New System.Data.DataTable()
Dim da As New System.Data.SqlClient.SqlDataAdapter(cmd3string, conn)
conn.Open()
da.Fill(dt)
conn.Close()
GridViewdoc.DataSource = dt
GridViewdoc.DataBind()
End If
End Sub
Protected Sub GridViewdoc_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridViewdoc.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim drview As DataRowView = TryCast(e.Row.DataItem, DataRowView)
'Find checkbox and checked/Unchecked based on values
Dim chkb As CheckBox = DirectCast(e.Row.FindControl("ApproveBox"), CheckBox)
If drview(8).ToString() = "Approve" Then
chkb.Checked = True
Else
End If
End If
End Sub
Protected Sub btnapprove_Click(sender As Object, e As System.EventArgs) Handles btnapprove.Click
Dim dt As Data.DataTable = Session("Approved")
Dim val As String
val = ""
Dim Oid As Integer
Dim conn As New System.Data.SqlClient.SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\surgerydb.mdf;Integrated Security=True;Connect Timeout=30")
For Each row As GridViewRow In GridViewdoc.Rows
Dim therowindex As Integer = row.RowIndex
Oid = Integer.Parse(GridViewdoc.DataKeys(therowindex).Value.ToString())
val = ""
Dim cb As CheckBox = row.FindControl("ApproveBox")
If cb.Checked Then
val = "Approved"
Else
val = "Disapproved"
End If
If Oid > 0 Then
Dim cmdstring As String = " UPDATE Order_pres SET Approved = #appr Where OrderID= #oid"
conn.Close()
conn.Open()
Dim cmd = New SqlCommand(cmdstring, conn)
cmd.Parameters.Add("#appr", Data.SqlDbType.NVarChar).Value = val
cmd.Parameters.Add("#oid", Data.SqlDbType.NVarChar).Value = Oid
Dim result As Integer
result = cmd.ExecuteNonQuery()
End If
Next
Dim cmd3string As String = " Select * From docgridview WHERE DoctorId = " & Session("DoctorId")
Dim dtm As New System.Data.DataTable()
Dim da As New System.Data.SqlClient.SqlDataAdapter(cmd3string, conn)
conn.Close()
conn.Open()
da.Fill(dtm)
conn.Close()
GridViewdoc.DataSource = dtm
GridViewdoc.DataBind()
End Sub
End Class
Hopefully someone can help - thank you :)
If the Approved field is NULL in Order_pres as long as no decision has been made about the order approval, you could try this:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGridViewData()
End If
End Sub
Protected Sub btnapprove_Click(sender As Object, e As System.EventArgs) Handles btnapprove.Click
...
For Each row As GridViewRow In GridViewdoc.Rows
...
Next
BindGridViewData()
End Sub
Protected Sub BindGridViewData()
Using conn As New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\surgerydb.mdf;Integrated Security=True;Connect Timeout=30")
Using cmd As New SqlCommand("SELECT DGV.* FROM docgridview DGV INNER JOIN Order_pres OP ON OP.OrderID = DGV.OrderID WHERE DGV.DoctorId = #DoctorId AND OP.Approved IS NULL", conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add(New SqlParameter("#DoctorId", Session("DoctorId")))
Dim dataAdapter As New SqlDataAdapter(cmd)
Dim dtm As New DataTable()
dataAdapter.Fill(dtm)
GridViewdoc.DataSource = dtm.DefaultView
GridViewdoc.DataBind()
End Using
End Using
End Sub
The query looks for records in docgridview for which the corresponding record in Order_pres has not been approved or disapproved yet.
N.B. The code above assumes that the following lines are present at the top of your VB code file:
Imports System.Data
Imports System.Data.SqlClient

sorting on vb.net gridview

trying to implement a sort on my gridview as below, its not quite working as I'd expect 1. it doesn't sort by the first column as i'd like, first column descending 2. when i click each of the columns they appear to change order but i can't determine what is actually sorting asc/desc. i really only need the first column which is the id to sort desc.
Imports System.Data.SqlClient
Public Class Query
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
BindGrid()
End If
End Sub
Protected Sub BindGrid()
Dim dt As New DataTable()
Dim strConnString As [String] = System.Configuration.ConfigurationManager.ConnectionStrings("constr").ConnectionString()
Dim strQuery As String = "select id,relates_to,'../../' + location as location from Files;"
Dim cmd As New SqlCommand(strQuery)
Dim con As New SqlConnection(strConnString)
Dim sda As New SqlDataAdapter()
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
ViewState("dt") = dt
GridView1.DataSource = dt
GridView1.DataBind()
Catch ex As Exception
Response.Write(ex.Message)
Finally
con.Close()
sda.Dispose()
con.Dispose()
End Try
End Sub
Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim item As String = e.Row.Cells(0).Text
For Each button As Button In e.Row.Cells(3).Controls.OfType(Of Button)()
If button.CommandName = "Delete" Then
button.Attributes("onclick") = "if(!confirm('Do you want to delete " + item + "?')){ return false; };"
End If
Next
End If
End Sub
Protected Sub OnRowDeleting(sender As Object, e As GridViewDeleteEventArgs)
Try
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("constr").ToString())
Dim cmd As New SqlCommand()
cmd.Connection = conn
cmd.CommandText = "DELETE FROM Files WHERE id = #id"
cmd.CommandType = CommandType.Text
Dim strBetID As String = GridView1.Rows(e.RowIndex).Cells(0).Text
cmd.Parameters.Add("#id", SqlDbType.Int).Value = strBetID
conn.Open()
cmd.ExecuteNonQuery()
End Using
BindGrid()
Catch ex As Exception
Response.Write(ex.Message)
End Try
End Sub
Private Sub LinkButtonUsers_Click(sender As Object, e As EventArgs) Handles LinkButtonUsers.Click
Response.Redirect("/Admin/Admin/Users.aspx")
End Sub
Private Sub LinkButtonTips_Click(sender As Object, e As EventArgs) Handles LinkButtonTips.Click
Response.Redirect("/Admin/Admin/Admin.aspx")
End Sub
Private Sub LinkButtonEmail_Click(sender As Object, e As EventArgs) Handles LinkButtonEmail.Click
Response.Redirect("/Admin/Admin/Email.aspx")
End Sub
Private Sub LinkButtonKnowledge_Click(sender As Object, e As EventArgs) Handles LinkButtonKnowledge.Click
Response.Redirect("/Admin/Admin/Knowledge.aspx")
End Sub
Protected Sub LinkButtonQuery_Click(sender As Object, e As EventArgs) Handles LinkButtonQuery.Click
Response.Redirect("/Admin/Admin/Query.aspx")
End Sub
Protected Sub OnPageIndexChanging(sender As Object, e As GridViewPageEventArgs)
GridView1.PageIndex = e.NewPageIndex
Me.BindGrid()
End Sub
Protected Sub GridView1_Sorting(sender As Object, e As GridViewSortEventArgs)
Dim dt As DataTable = ViewState.Item("dt")
Dim dv As DataView = dt.DefaultView
Dim sd As String = ""
If Not dt Is Nothing Or Not dt Is "" Then
If e.SortDirection.ToString.Contains("asc") Then
sd = "asc"
ElseIf e.SortDirection.ToString.Contains("desc") Then
sd = "desc"
Else
sd = "asc"
End If
End If
Try
dv.Sort = e.SortExpression + " " + sd
dt = dv.ToTable
GridView1.DataSource = dt
GridView1.DataBind()
Catch ex As Exception
End Try
End Sub
End Class
aspx is as such:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDeleting="OnRowDeleting"
OnRowDataBound="OnRowDataBound" EnableModelValidation="True" AllowSorting="true"
OnSorting="GridView1_Sorting" AllowPaging="True" OnPageIndexChanging="OnPageIndexChanging">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="id" />
<asp:BoundField DataField="relates_to" HeaderText="relates_to" SortExpression="relates_to" />
<asp:TemplateField HeaderText="Preview Image" SortExpression="location">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl='<%# Eval("location")%>'
Width="100px" Height="100px" Style="cursor: pointer" OnClientClick="return LoadDiv(this.src);" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
</asp:GridView>
am tempted to re-write the lot again using another approach as i have kind of cobbled this together from a couple of sources on the net and presumed it would be okay? probably something minor like the viewstate aspect but can't fathom it out at the moment!?..
Instead of storing the DataTable in the ViewState, you can call BindGrid from the Sorting event to populate the GridView. If you include the data sorting in that method, it will apply in all situations.
The sorting parameters can be stored in the ViewState (or in Session):
Protected Property SortExpression As String
Get
Dim value as Object = ViewState("SortExpression")
Return If(Not IsNothing(value), CStr(value), "id")
End Get
Set(value As String)
ViewState("SortExpression") = value
End Set
End Property
Protected Property IsAscendingSort As Boolean
Get
Dim value as Object = ViewState("IsAscendingSort")
Return If(Not IsNothing(value), CBool(value), False)
End Get
Set(value As Boolean)
ViewState("IsAscendingSort") = value
End Set
End Property
They can be set in the Sorting event handler:
Protected Sub GridView1_Sorting(sender As Object, e As GridViewSortEventArgs)
If e.SortExpression = SortExpression Then
IsAscendingSort = Not IsAscendingSort
Else
SortExpression = e.SortExpression
End If
BindGrid()
End Sub
And used in the BindGrid method:
Protected Sub BindGrid()
...
sda.Fill(dt)
Dim dv As DataView = dt.DefaultView
dv.Sort = SortExpression + " " + If(IsAscendingSort, "ASC", "DESC")
GridView1.DataSource = dv
GridView1.DataBind()
...
End Sub

Adding filter to one hearder column of the Gridview

I would like to create a filter to one of my header column [Carrier] , here is the code of gridview that I've created:
index.aspx:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="cr_OnSelectedIndexChanged"
DataSourceID="SqlDataSource1" DataTextField="CARRIER" DataValueField="CARRIER">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:MybaseConnectionString %>"
SelectCommand="SELECT DISTINCT [CARRIER] FROM [TABLE]">
</asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" Height="150px" Width="284px">
</asp:GridView>
index.aspx.vb
Inherits System.Web.UI.Page
Dim cx As New SqlConnection("Data Source=.\SQLEXPRESS;database=Mybase;Integrated Security=True;")
Dim cmd As New SqlCommand
Dim da As New SqlDataAdapter
Dim dt As New DataTable
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
cmd.Connection = cx
cmd.CommandText = "select cl1, Carrier, cl2, cl3 from table"
da = New SqlDataAdapter(cmd)
da.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
End Sub
Any one can help Please!
Thank you..
take one textbox
<asp:TextBox runat="server" ID="txtSearch"/>
on button click event
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
cmd.Connection = cx
cmd.CommandText = "select cl1, Carrier, cl2, cl3 from table where Carrier='"+txtSearch.Text+"'"
da = New SqlDataAdapter(cmd)
da.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
I suggest putting a drop down list in the header of the column you wish to filter (in your case Carrier). Then you can wire up the OnSelectedIndexChanged event of the drop down list to handle the actual filtering of your column's data. An older, but still relevant example of this technique is here:
ASP.NET GridView Column Filtering
Assuming Carrier is field of type nvarchar(200) and filtering should be done after user clicks on Button1 (which is not visible in markup), body of method Button1_Click should look like:
Dim sql As String = "select cl1, Carrier, cl2, cl3 from table where Carrier = #Carrier"
Using cn As New SqlConnection("Data Source=.\SQLEXPRESS;database=Mybase;Integrated Security=True;"), _
cmd As New SqlCommand(sql, cn)
cmd.Parameters.Add("#Carrier", SqlDbTypes.NVarChar, 200).Value = DropDownList1.SelectedValue
da = New SqlDataAdapter(cmd)
da.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
You might are in need to look at RowFilter property of DataGrid. Have a look at this link, which include sample code.

DropDownList after postback all values/index lost

I'm running into a little problem with a gridview and a dropdownlist. I can get the dropdownlist to load initially, but when it autopostback's it returns with no value. I am populating the dropdownlist in the RowEditing sub. I'm guessing that I must somehow rebind in the RowDataBound sub, but don't know how to go about it. If I try to find the control's SelectedValue I end up with nothing.
VB Code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
bindGridView()
End If
End Sub
'Menu Click
'bindGridView
Public Sub bindGridView(Optional ByVal sortExp As String = "", Optional ByVal sortDir As String = "")
Dim strConnString As String = ConfigurationManager.ConnectionStrings("WEBConnectionString").ConnectionString
Dim conn As SqlConnection = New SqlConnection(strConnString)
conn.Open()
Dim strProgramNumber As String = 5
Dim strRecordType As String = "Input Source"
Dim strProgramInformation As String = "\\path\to\file"
Dim sql As String
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = conn
If sortExp <> String.Empty Then
sortExp = (sortExp & " " & sortDir).ToString
sql = "SELECT tblPrgTrackPrograms.ProgramNumber, " & _
"tblPrgTrackPrograms.ProgramName, " & _
"tblPrgTrackPrograms.ProgramStatus, " & _
"tblPrgTrackProgramDocumentation.RecordType, " & _
"tblPrgTrackProgramDocumentation.ProgramInformation " & _
"FROM tblPrgTrackPrograms INNER JOIN tblPrgTrackProgramDocumentation ON " & _
"tblPrgTrackPrograms.ProgramNumber = tblPrgTrackProgramDocumentation.ProgramNumber ORDER BY " & _
"#sortExp"
cmd.Parameters.AddWithValue("sortExp", sortExp)
Else
sql = "SELECT tblPrgTrackPrograms.ProgramNumber, " & _
"tblPrgTrackPrograms.ProgramName, " & _
"tblPrgTrackPrograms.ProgramStatus, " & _
"tblPrgTrackProgramDocumentation.RecordType, " & _
"tblPrgTrackProgramDocumentation.ProgramInformation " & _
"FROM tblPrgTrackPrograms INNER JOIN tblPrgTrackProgramDocumentation ON " & _
"tblPrgTrackPrograms.ProgramNumber = tblPrgTrackProgramDocumentation.ProgramNumber"
End If
cmd.CommandText = sql
Dim myDataSet As New DataSet()
Dim mySQLAdapter As New SqlDataAdapter(cmd)
mySQLAdapter.SelectCommand.Connection = conn
mySQLAdapter.Fill(myDataSet)
conn.Close()
gvProgramDetails.DataSource = myDataSet
gvProgramDetails.DataBind()
End Sub
'ProgramDetails Load
Protected Sub gvProgramDetails_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvProgramDetails.Load
bindGridView()
End Sub
'ProgramDetails Paging
Protected Sub gvProgramDetails_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gvProgramDetails.PageIndexChanging
gvProgramDetails.PageIndex = e.NewPageIndex
bindGridView()
End Sub
'ProgramDetails Sorting
Protected Sub gvProgramDetails_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles gvProgramDetails.Sorting
Dim SortDirection As String
If Session("SortDirection") = vbNullString Then
Session("SortDirection") = "DESC"
Else
SortDirection = Session("SortDirection").ToString
If SortDirection = "ASC" Then
SortDirection = "DESC"
ElseIf SortDirection = "DESC" Then
SortDirection = "ASC"
Else
SortDirection = "ASC"
End If
bindGridView(e.SortExpression, Session("SortDirection"))
'Need to store sort info in view state
Session("SortDirection") = SortDirection
End If
End Sub
'ProgramDetails RowEditing
Protected Sub gvProgramDetails_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gvProgramDetails.RowEditing
Dim lbl As Label = CType(gvProgramDetails.Rows(e.NewEditIndex).FindControl("lblRecordType"), Label)
Dim strValue As String = lbl.Text
gvProgramDetails.EditIndex = e.NewEditIndex
bindGridView()
Dim row As GridViewRow = gvProgramDetails.Rows(e.NewEditIndex)
Dim strConnString As String = ConfigurationManager.ConnectionStrings("CSPaperWEBConnectionString").ConnectionString
Dim ddlRecordType As DropDownList = CType(row.FindControl("ddlRecordType"), DropDownList)
Dim conn As SqlConnection = New SqlConnection(strConnString)
conn.Open()
Dim sql As String
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = conn
sql = "select RecordType from [tblPrgTrackValidRecordTypes] "
cmd.CommandText = sql
Dim myDataSet As New DataSet()
Dim mySQLAdapter As New SqlDataAdapter(cmd)
mySQLAdapter.SelectCommand.Connection = conn
mySQLAdapter.Fill(myDataSet)
conn.Close()
If ddlRecordType IsNot Nothing Then
ddlRecordType.DataTextField = "RecordType"
ddlRecordType.DataValueField = "RecordType"
ddlRecordType.DataSource = myDataSet
ddlRecordType.SelectedValue = strValue
ddlRecordType.DataBind()
End If
End Sub
Protected Sub gvProgramDetails_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvProgramDetails.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim ctrl As Control = e.Row.FindControl("ddlRecordType")
If ctrl IsNot Nothing Then
Dim ddlRecordType As DropDownList = ctrl
MsgBox(ddlRecordType.SelectedValue)
End If
End If
End Sub
'ProgramDetails RowUpdating
Protected Sub gvProgramDetails_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles gvProgramDetails.RowUpdating
Dim ddlRecordType As DropDownList = gvProgramDetails.Rows(e.RowIndex).FindControl("ddlRecordType")
MsgBox(ddlRecordType.SelectedValue)
gvProgramDetails.EditIndex = -1
bindGridView()
End Sub
'ProgramDetails RowCancelingEdit
Protected Sub gvProgramDetails_RowCancelingEdit1(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles gvProgramDetails.RowCancelingEdit
gvProgramDetails.EditIndex = -1
bindGridView()
End Sub
'ProgramDetails RowDeleting
Protected Sub gvProgramDetails_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles gvProgramDetails.RowDeleting
Dim strConnString As String = ConfigurationManager.ConnectionStrings("WEBConnectionString").ConnectionString
Dim conn As SqlConnection = New SqlConnection(strConnString)
conn.Open()
Dim strProgramNumber As String = 5
Dim strRecordType As String = "Input Source"
Dim strProgramInformation As String = "\\path\to\file"
Dim sql As String = "delete from tblPrgTrackProgramDocumentation where ProgramNumber = #ProgramNumber and RecordType = #RecordType and ProgramInformation = #ProgramInformation"
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = conn
cmd.CommandText = sql
cmd.Parameters.AddWithValue("ProgramNumber", strProgramNumber)
cmd.Parameters.AddWithValue("RecordType", strRecordType)
cmd.Parameters.AddWithValue("ProgramInformation", strProgramInformation)
cmd.ExecuteNonQuery()
cmd.Dispose()
bindGridView()
End Sub
ASP front end
<ajx:UpdatePanel ID="ajaxpanel" runat="server">
<ContentTemplate>
<asp:GridView ID="gvProgramDetails" runat="server" AutoGenerateColumns="False"
CssClass="gridview" DataKeyNames="ProgramNumber" AllowPaging="True" PageSize="3" AllowSorting="True" >
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete" OnClientClick="return confirm('Are you sure you want to delete this record');"></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
</EditItemTemplate>
<ControlStyle CssClass="button delete" />
</asp:TemplateField>
<asp:CommandField ControlStyle-CssClass="button save" ShowEditButton="True">
<ControlStyle CssClass="button save" />
</asp:CommandField>
<asp:BoundField DataField="ProgramNumber" HeaderText="ProgramNumber"
InsertVisible="False" ReadOnly="True" SortExpression="ProgramNumber" />
<asp:BoundField DataField="ProgramName" HeaderText="ProgramName" ReadOnly="True"
SortExpression="ProgramName" />
<asp:BoundField DataField="ProgramStatus" HeaderText="ProgramStatus" ReadOnly="True"
SortExpression="ProgramStatus" />
<asp:TemplateField HeaderText="RecordType" SortExpression="RecordType">
<EditItemTemplate>
<asp:DropDownList ID="ddlRecordType" runat="server" autopostback="True">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblRecordType" runat="server" Text='<%# Bind("RecordType") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ProgramInformation" HeaderText="ProgramInformation"
SortExpression="ProgramInformation" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:WEBConnectionString %>"
SelectCommand="SELECT * FROM [tblPrgTrackValidRecordTypes]"></asp:SqlDataSource>
</ContentTemplate>
</ajx:UpdatePanel>
For those of you who answer drag the control in from the toolbox, create datasource, and set bind("RecordType") please don't. I've tried it that way and the value would always post back with whatever Recordtype was. So unless if you can solve that version of this gridview don't use drag/drop control solution. I'm scratching my brain to solve this one.
Update
I created under App_Code Process/ddlRecordType.vb
Imports Microsoft.VisualBasic
Namespace processes.ProgramTrack.dllRecordType
Public Class ddlRecordType
Public Sub ddlRecordType()
End Sub
Public Function GetRecords() As DataSet
Dim conn As New SqlConnection
Dim cmd As New SqlCommand
conn.ConnectionString = ConfigurationManager.ConnectionStrings("WEBConnectionString").ConnectionString.ToString
cmd.CommandText = "select RecordType from [tblPrgTrackValidRecordTypes] "
cmd.Connection = conn
Dim myDataSet As New DataSet()
Dim mySQLAdapter As New SqlDataAdapter(cmd)
mySQLAdapter.Fill(myDataSet)
Return myDataSet
End Function
End Class
End Namespace
My markup then looks like this.
<asp:DropDownList ID="ddlRecordType" DatasourceID="odsRecordType" DataTextField="RecordType" DataValueField="RecordType" runat="server" autopostback="True" > </asp:DropDownList>
<asp:ObjectDataSource ID="odsRecordType" runat="server" TypeName="processes.ProgramTrack.dllRecordType.ddlRecordType" SelectMethod="GetRecords"></asp:ObjectDataSource>
Then I get the same problem as before about the DDL not maintaining it's value at postback. Should I start a new Question or continue with this one?
Update to fix the DDL not maintaining. Disable Viewstate for the gridview.
<asp:GridView ID="gvProgramDetails" runat="server" AutoGenerateColumns="False" CssClass="gridview"DataKeyNames="ProgramNumber" AllowPaging="True" PageSize="10" EnableViewState="False" AllowSorting="True">
Try creating an objectDataSource for the DDL, and use that. The problem is that the DDL has to be initialized at page load, or on page init, OR via a DataSource control. If you weren't using the Ajax UpdatePanel (go ahead, take it out, watch your code work, it should anyways) then you would be able to do it like this.
If you'll introduce an ObjectDataSource (and you can pass parameters to it too) then you should end up with what you want.
Edit:
I'm going to provide code from a project of mine, so that you can see how I'm using it. This code will not be perfect to your needs, but will show you how to do what you want.
namespace Appropriate.Namespace.Here {
public class MyType {
public List<KeyValuePair<string, string>> GetRoles() {
List<KeyValuePair<string, string>> l = new List<KeyValuePair<string, string>>();
l.Add( new KeyValuePair<string, string>( "Level1", "Analyst" ) );
l.Add( new KeyValuePair<string, string>( "Level2", "Customer Service" ) );
l.Add( new KeyValuePair<string, string>( "Level3", "Customer Service Manager" ) );
l.Add( new KeyValuePair<string, string>( "Level4", "Full-Access User" ) );
l.Add( new KeyValuePair<string, string>( "Level5", "Super User" ) );
return l;
}
}
}
<asp:DropDownList ID="cmbRoles" runat="server" AutoPostBack="False" DataSourceID="odsRoles" DataTextField="Value" DataValueField="Key" />
<asp:ObjectDataSource ID="odsRoles" runat="server" TypeName="Appropriate.Namespace.Here.MyType" SelectMethod="GetRoles" />
Notice how the namespace and typename work together to give me the SelectMethod? I'm not providing an override on the select parameters, altho you could. You would do that in the page backing code, and I could give some insight on that as well, but I'm trying to not be entirely overly complex.
Notice how I'm returning a List from the method? And I'm just defining it in that method? You could just as easily do a database call there.

ASP.net: GridView columns repeating after paging

I have a GridView that has it's columns added dynamically in codebehind. I've added paging to the GridView, and it works, but when it goes to the next page, it adds the columns again.
So the GridView starts out with 2 columns (Last Name and First Name) added from codebehind. Then I go to it's next page, and it properly loads the next page of results, but now with 4 columns (Last Name, First Name, Last Name, First Name).
What am I doing wrong here?
Here's the code for the GridView:
<asp:GridView id="GridView3" runat="server" AutoGenerateColumns="False"
EmptyDataText="There are no data records to display."
AllowPaging="True"
OnPageIndexChanging="GridView3_PageIndexChanging"
CssClass="GridViewStyle" GridLines="None" Width="100%">
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="EmplID"
DataNavigateUrlFormatString="EmployeeProfile.aspx?EmplID={0}"
DataTextField="EmplID"
DataTextFormatString= "<img src='Images/icons/document-search-result.png' alt='View'/> <u>View</u>" >
<ControlStyle CssClass="titleLinksB" />
<ItemStyle Wrap="False" />
</asp:HyperLinkField>
</Columns>
</asp:GridView>
Here's the code for the codebehind:
Private Sub loadDynamicGrid()
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
Dim lastName As String
Dim linkText As String
lastName = Request.QueryString("lastName")
connetionString = ConfigurationManager.ConnectionStrings("dbConnectionString").ConnectionString.ToString()
sql = "SELECT * FROM [EmployeeList] Where [lastname] like '" & lastName & "%' order by lastname"
connection = New SqlConnection(connetionString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds)
Dim curLastName As New BoundField
curLastName.HeaderText = "Last Name"
curLastName.DataField = "LastName"
GridView3.Columns.Insert(0, curLastName)
Dim curFirstName As New BoundField
curFirstName.HeaderText = "First Name"
curFirstName.DataField = "FirstName"
GridView3.Columns.Insert(1, curFirstName)
GridView3.Visible = True
GridView3.DataSource = ds
GridView3.DataBind()
adapter.Dispose()
command.Dispose()
connection.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
And finally the Paging code:
Protected Sub GridView3_PageIndexChanging(ByVal sender As [Object], ByVal e As GridViewPageEventArgs)
GridView3.PageIndex = e.NewPageIndex
GridView3.DataBind()
End Sub
Any help is greatly appreciated!
I assume that you're calling loadDynamicGrid on every postback and not only If Not Page.IsPostBack.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
loadDynamicGrid()
End If
End Sub

Resources