ASP.net: GridView columns repeating after paging - asp.net

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

Related

Edit Gridview update issue

I have got a gridview which when you press select on a row it transfers you to another gridview page,
which displays more columns from that table to give more detail about that row.
I know how to do this using:
<asp:HyperLinkField DataNavigateUrlFields="MISAppID" DataNavigateUrlFormatString="ApplicationsDetails.aspx?MISAppID={0}" Text="Select" />
In the 1st Gridview then using a Stored-procedure on the second page it displays the correct row using the ID field.
In my current site on the second page, I have added an edit button that does edit the row correctly in my database but on completion, it breaks the site and I can't work out how to get it to just refresh the gridview
This is the error I get:
Exception Details: System.NotSupportedException: Updating is not
supported by data source 'SqlDataSource1' unless UpdateCommand is
specified.
Is it the case that my BindGrid is missing something or is the way I am using my Stored-procedure?
Here is my VB code:
Public Sub BindGrid() Handles SqlDataSource1.Selecting
End Sub
Protected Sub OnRowEditing(sender As Object, e As GridViewEditEventArgs)
GridView1.EditIndex = e.NewEditIndex
Me.BindGrid()
End Sub
Protected Sub OnRowUpdating(sender As Object, e As GridViewUpdateEventArgs)
Dim row As GridViewRow = GridView1.Rows(e.RowIndex)
Dim misappId As Integer = Convert.ToInt32(GridView1.DataKeys(e.RowIndex).Values(0))
Dim application As String = TryCast(row.Cells(2).Controls(0), TextBox).Text
Dim url As String = TryCast(row.Cells(3).Controls(0), TextBox).Text
Dim access_group As String = TryCast(row.Cells(4).Controls(0), TextBox).Text
Dim creator_ein As String = TryCast(row.Cells(5).Controls(0), TextBox).Text
Dim data_location As String = TryCast(row.Cells(6).Controls(0), TextBox).Text
Dim purpose As String = TryCast(row.Cells(7).Controls(0), TextBox).Text
Dim active As String = TryCast(row.Cells(8).Controls(0), TextBox).Text
Dim business_owner As String = TryCast(row.Cells(9).Controls(0), TextBox).Text
Dim area As String = TryCast(row.Cells(10).Controls(0), TextBox).Text
Dim constr As String = ConfigurationManager.ConnectionStrings("myLocalConnectionString").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("UPDATE tbl_AutomationCompassApplications SET Application = #Application, URL = #URL, Access_Group = #Access_Group, Creator_EIN = #Creator_EIN, Data_location = #Data_location, Purpose = #Purpose, Active = #Active, Business_Owner = #Business_Owner, Area = #Area WHERE MISAppID = #MISAppID")
cmd.Parameters.AddWithValue("#MISAppID", misappId)
cmd.Parameters.AddWithValue("#Application", application)
cmd.Parameters.AddWithValue("#URL", url)
cmd.Parameters.AddWithValue("#Access_Group", access_group)
cmd.Parameters.AddWithValue("#Creator_EIN", creator_ein)
cmd.Parameters.AddWithValue("#Data_location", data_location)
cmd.Parameters.AddWithValue("#Purpose", purpose)
cmd.Parameters.AddWithValue("#Active", active)
cmd.Parameters.AddWithValue("#Business_Owner", business_owner)
cmd.Parameters.AddWithValue("#Area", area)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
GridView1.EditIndex = -1
Me.BindGrid()
End Sub
Ok, say we have a list of hotels - we want to display them, and then click on a row to eit.
(and you writing WAY too much code here).
So, lets say we drop in a gridview. Use the connection wizard - let it generate the markup.
THEN REMOVE the data source on the page, remove the datasource property of the gridview.
So, in less time then it takes me to write above? We have this markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="cmdView" runat="server" Text="Edit"
PK = '<%# Container.DataItemIndex %>' OnClick="cmdView_Click" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:BoundField DataField="City" HeaderText="City" />
</Columns>
</asp:GridView>
Note the cool trick I used to get the PK row index.
When you are looking at the grid, you can't double click on the button to wire up a event (code behind), but you CAN DO THIS!!!!
Note VERY care full in above - I typed in OnClick "=", when you HIT "=", then NOTE the inteli-sense that popped up - the create NEW event is what we need. Click on create new event - NOTHING seems to happen, but if we NOW go to code behind, we have a code stub for the button!!!
And note how I needed/wanted the PK row value - so I just shoved in and created my OWN custom attribute for that button. ("PK").
Ok, so our code to load up the grid is now this - and I included the button click code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack = False Then
LoadGrid()
End If
End Sub
Sub LoadGrid()
Dim strSQL As String
strSQL = "SELECT * from tblHotels Order by HotelName"
Using cmdSQL As New SqlCommand(strSQL, New SqlConnection(My.Settings.TEST3))
cmdSQL.Connection.Open()
Dim MyTable As New DataTable
MyTable.Load(cmdSQL.ExecuteReader)
GridView1.DataSource = MyTable
GridView1.DataBind()
Session("MyTable") = MyTable
End Using
End Sub
Protected Sub cmdView_Click(sender As Object, e As EventArgs)
Dim MyBtn As Button = sender
Session("RowID") = MyBtn.Attributes.Item("PK")
Response.Redirect("~/EditHotel.aspx")
End Sub
Look how clean and simple the above is!!! I find this as easy say as MS-Access coding!!!
Ok, so the grid now looks like this:
Note the button click code.
So, our markup is this for the new page (to edit hte ONE row).
<div style="float:left;width:20%">
<div style="text-align:right">
First Name :<asp:TextBox ID="txtFirstname" runat="server" Width="150"></asp:TextBox> <br />
Last Name :<asp:TextBox ID="txtLastname" runat="server" Width="150"></asp:TextBox> <br />
Hotel Name :<asp:TextBox ID="txtHotel" runat="server" Width="150"></asp:TextBox> <br />
City :<asp:TextBox ID="txtCity" runat="server" Width="150"></asp:TextBox> <br />
Active :<asp:CheckBox ID="Active" runat="server" Width="150"></asp:CheckBox>
</div>
</div>
<div style="clear:both">
<br />
<asp:Button ID="cmdSave" runat="server" Text ="Save " />
<asp:Button ID="cmdCancel" runat="server" Text="Cancel" Style="margin-left:20px" />
</div>
</form>
and it looks like this:
and the load code and save button code for this page?
This:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack = False Then
LoadInfo()
End If
End Sub
Sub LoadInfo()
Dim MyTable As DataTable = Session("MyTable")
Dim MyRow As DataRow = MyTable.Rows(Session("RowID"))
txtFirstname.Text = MyRow("FirstName")
txtLastname.Text = MyRow("LastName")
txtCity.Text = MyRow("City")
txtHotel.Text = MyRow("HotelName")
Active.Checked = MyRow("Active")
End Sub
Protected Sub cmdSave_Click(sender As Object, e As EventArgs) Handles cmdSave.Click
Dim MyTable As DataTable = Session("MyTable")
Dim MyRow As DataRow = MyTable.Rows(Session("RowID"))
MyRow("FirstName") = txtFirstname.Text
MyRow("LastName") = txtLastname.Text
MyRow("City") = txtCity.Text
MyRow("HotelName") = txtHotel.Text
MyRow("Active") = Active.Checked
Using cmdSQL As New SqlCommand("SELECT * from tblHotels where ID = 0",
New SqlConnection(My.Settings.TEST3))
Dim da As New SqlDataAdapter(cmdSQL)
Dim cmdUpdate As New SqlCommandBuilder(da)
da.Update(MyTable)
End Using
Response.Redirect("~/MyTours.aspx")
End Sub
Again, look how easy, clean and readable the code is.
Study the above example - you see that you don't need all that parameters code, and you see how little code is in fact required to select a row - jump to page to edit, and then you hit save - update the data and jump back to the grid row page.

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

Trouble with Listbox bind inside Gridview

I am a AS400 programmer asked to write a program in asp.net using vb.net. I have never done this before and I am having issues with populating a listbox in Gridview. I have researched this subject for days but all the code I have tried, found in examples, do not work. Please forgive any really bad code, with me being so new to .net, I am sure this could be written much better. I appreciate any help you may be able to offer. the grid is "AdjusterList" and the Listbox is called "MAICD". I think the 'failing/bad' code in
Public Sub AdjusterList_RowDataBound. It is giving me a null exception error the line before the databind; oCtrl.DataSource = oRs
I am using code given to me by a senior .net programmer, whom is not able to offer any more assistance to this newbie. Just Fyi....
Here is my aspx.
<div id="div1" runat="server">
<asp:GridView ID="AdjusterList" runat="server" Width="1100px"
ClientIDMode="Static" AllowSorting="True"
AutoGenerateColumns="False"
OnRowCommand="AdjusterList_RowCommand"
OnRowEditing="AdjusterList_RowEditing"
OnRowUpdating="AdjusterList_RowUpdating"
OnRowDeleting="AdjusterList_RowDeleting"
OnRowCancelingEdit="AdjusterList_RowCancelingEdit"
OnRowDataBound="AdjusterList_RowDataBound"
DataKeyNames="INSCD, INSSEQ"
ShowHeaderWhenEmpty="True" EditRowStyle-BackColor="#FF9900" PageSize="20"
EmptyDataText="NO RECORDS FOUND FOR THIS INSURER"
ShowFooter="True"EnableViewState="true">
<EditRowStyle BackColor="#FF9900" />
<RowStyle BackColor="White" ForeColor="Black" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton id="btnedit" runat="server" CommandName="Edit"/>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton id="btnupdate" runat="server" CommandName="Update" Text="Save" />
<asp:LinkButton id="btncancel" runat="server" CommandName="Cancel" Text=Cancel"/>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton id="btninsert" runat="server" CommandName="Insert" Text="Insert"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Mail Code" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblmaicd" runat="server" Text='<%# Bind("MAICD")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:ListBox ID="MAICD" runat="server" Rows="1"DataTextField="Text"
DataValueField='<%# Bind("MAICD")%></asp:ListBox>
</EditItemTemplate>
<FooterTemplate>
<asp:ListBox ID="MAICD" runat="server" width="200" DataTextField="Text">
</asp:ListBox>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My code behind...
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.OleDb
Public Class EditAdjusterData
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e AsSystem.EventArgs)
Dim sAdjuster As String = Session("Adjuster")
Dim sSeqNo As String = Session("SeqNo")
PopulateEdit(sAdjuster, sSeqNo, dateok)
If IsPostBack Then
'divEdit.Visible = False
'divSelect.Visible = True
'ShowForm()
Else
AdjusterList.DataBind()
'divEdit.Visible = True
'divSelect.Visible = False
End If
End Sub
Protected Sub PopulateEdit(sValue As String, sValue2 As String, sValue3 As String)
' CALL TO PGRTSTLIB FILE INSP TO GET INSURER NAME
' 2ND CALL TO PGRTSTLIB FILE INSD
Dim oConn As New OleDbConnection()
Dim sConn As String = ""
Dim oCmd As New OleDbCommand()
Dim oAdapter As New OleDbDataAdapter()
Dim oRs As DataSet = New DataSet
Dim sSql As String = ""
sConn = "Provider=IBMDA400.DataSource.1;
oConn = New OleDb.OleDbConnection(sConn)
oConn.Open()
sSql = "SELECT INSCD, INSSEQ, MAICD, MAISEQ, (substr(char(EFFDT),5,2) || '-' || substr(char(EFFDT),7,2) || '-' || substr(char(EFFDT),1,4)) AS EFFDT, (substr(char(CANDT),5,2) || '-' || substr(char(CANDT),7,2) || '-' || substr(char(CANDT),1,4)) AS CANDT, ACCFIL FROM PGRTSTLIB.INSD WHERE INSCD = '" & sValue & "' "
oCmd = New OleDbCommand(sSql, oConn)
Session(INSCD) = INSCD
Session(EFFDT) = EFFDT
Session(MAICD) = MAICD
Session("CANDT") = CANDT
oCmd.CommandType = CommandType.Text
oAdapter.SelectCommand = oCmd
oAdapter.Fill(oRs, "Data")
Dim sMailCode As String = " "
Dim sMailSeq As String = " "
Dim pRow As DataRow
For Each pRow In oRs.Tables("Data").Rows
sMailCode = pRow("MAICD").ToString()
Next
Session(sMailCode) = MAICD
Session(MAICD) = sMailCode
Session(sMailCode) = sMailCode
AdjusterList.DataSource = oRs
'AdjusterList.DataBind()
'If sMailCode <> " " Then
' PopulateMailCode(sMailCode)
'End If
oRs.Dispose()
oAdapter.Dispose()
oCmd.Dispose()
oConn.Dispose()
End Sub
Protected Sub AdjusterList_PageIndexChanging(ByVal sender As Object,
ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs)
AdjusterList.PageIndex = e.NewPageIndex
AdjusterList.DataBind()
End Sub
Protected Sub AdjusterList_RowCommand(ByVal sender As Object,
ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
End Sub
Protected Sub AdjusterList_RowCreated(ByVal sender As Object,
ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
End Sub
Public Sub AdjusterList_RowDataBound(ByVal Sender As Object,
ByVal e As GridViewRowEventArgs) Handles AdjusterList.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.FindControl("MAICD") IsNot Nothing Then
Dim MAICD As ListBox = e.Row.FindControl("MAICD")
'If (e.Row.RowState And DataControlRowState.Edit) > 0 Then
BindAjusterList()
End If
End If
End Sub
Public Sub BindAjusterList()
Dim oConn As New OleDbConnection()
Dim sConn As String = ""
Dim oCmd As New OleDbCommand()
Dim oAdapter As New OleDbDataAdapter()
Dim oRs As DataSet = New DataSet
Dim sSql As String = ""
sConn = "Provider=IBMDA400.DataSource.1; "
oConn = New OleDb.OleDbConnection(sConn)
oConn.Open()
'sSql = "SELECT MAICD as Value, MAICD AS Text from PGRTSTLIB.INSM order by MAICD"
sSql = "SELECT MAICD As Value, MAICD AS TEXT from PGRTSTLIB.INSM"
oCmd = New OleDbCommand(sSql, oConn)
'oCmd.Parameters.Add(New SqlParameter("#Type", Insurer))
oCmd.CommandType = CommandType.Text
oAdapter.SelectCommand = oCmd
oAdapter.Fill(oRs, "ListBox")
Dim oCtrl As ListBox
oCtrl = AdjusterList.FindControl("MAICD")
oCtrl.Items.Add(New ListItem("", ""))
oCtrl.DataSource = oRs
oCtrl.DataBind()
oCtrl.Items.Insert(0, New ListItem(String.Empty, String.Empty))
If Len(sValue) > 0 Then
oCtrl.SelectedValue = sValue
Else
sValue = " "
End If
oRs.Dispose()
oAdapter.Dispose()
oCmd.Dispose()
oConn.Dispose()
End Sub
Public Sub AdjusterList_RowEditing(ByVal sender As Object,
ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs)
AdjusterList.EditIndex = e.NewEditIndex
AdjusterList.DataBind()
End Sub
Protected Sub AdjusterList_RowUpdating(ByVal sender As Object,
ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs)
' Dim row As GridViewRow = DirectCast(SubsidaryList.Rows(e.RowIndex), GridViewRow)
Dim INSCD As String = DirectCast(AdjusterList.Rows(e.RowIndex).Cells (0).FindControl ("INSCD"), TextBox).Text
Dim INSSEQ As String = DirectCast(AdjusterList.Rows(e.RowIndex).Cells(1).FindControl("INSSEQ"), TextBox).Text
Dim MAICD As String = DirectCast(AdjusterList.Rows(e.RowIndex).Cells(2).FindControl("MAICD"), ListBox).Text
Dim MAISEQ As String = DirectCast(AdjusterList.Rows(e.RowIndex).Cells(3).FindControl("MAISEQ"), TextBox).Text
Dim EFFDT As String = DirectCast(AdjusterList.Rows(e.RowIndex).Cells(4).FindControl("EFFDT"), TextBox).Text
Dim CANDT As String = DirectCast(AdjusterList.Rows(e.RowIndex).Cells(5).FindControl("CANDT"), TextBox).Text
Dim ACCFIL As String = DirectCast(AdjusterList.Rows(e.RowIndex).Cells(6).FindControl("ACCFIL"), TextBox).Text
AdjusterList.EditIndex = -1
AdjusterList.DataBind()
' New Data to DataBind to sql datasource and resend page after RECORD updated
Response.Redirect("EditAdjusterData.aspx")
End Sub
Protected Sub AdjusterList_RowCancelingEdit() Handles AdjusterList.RowCancelingEdit
AdjusterList.EditIndex = -1
AdjusterList.DataBind()
End Sub
End Class
I am so new to .net and I may not fully understand every example. I think the senior .net programmers think it is funny : (
Thanks so much and please feel free to contact me with any help you may be able to offer. I just need the darn listbox to populate. I removed any code I considered unrelated to this listbox issue.
In your markup, you should change the DataValueField property of your ListBox to the "Value" string, because it's the alias you are giving to the property in the query ("SELECT MAICD As Value, MAICD AS TEXT from PGRTSTLIB.INSM"):
<asp:ListBox ID="MAICD" runat="server" Rows="1"DataTextField="Text" DataValueField="Value"></asp:ListBox>
Also, in RowDataBound event, you are retrieving the ListBox instance for that row using the FindControl method, but then you are retrieving it again in the BindAjusterList() method. Try changing the method to receive the control found:
Public Sub AdjusterList_RowDataBound(ByVal Sender As Object, ByVal e As GridViewRowEventArgs) Handles AdjusterList.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.FindControl("MAICD") IsNot Nothing Then
Dim MAICD As ListBox = e.Row.FindControl("MAICD")
BindAjusterList(MAICD)
End If
End If
End Sub
Public Sub BindAjusterList(ByVal oCtrl As ListBox)
' existing logic
oCtrl.Items.Add(New ListItem("", ""))
oCtrl.DataSource = oRs
oCtrl.DataBind()
' existing logic
End Sub

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.

dynamically build html table on page load

Edit for vhinn
I want it to look like this:
I am trying to build an html table dynamically on pageload with variables from a database.
this is an example strictly html http://jsfiddle.net/jdv590/daCum/1/
code:
Private Sub brothersgird()
Dim html As New StringBuilder
Dim sql As String = "select Name, Hometown, Picture, Class from brothers",
connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=~/App_Data/Members.accdb;Persist Security Info=False;",
conn As New OleDbConnection(connstring),
myCommand As New OleDbCommand(sql, conn),
namevar As String,
classvar As String,
hometownvar As String
Dim x As Integer = 1
conn.Open()
Dim dr As OleDbDataReader = myCommand.ExecuteReader
html.Append("<table>")
Do While dr.Read
' imagevar = dr("Picture")
namevar = dr("Name")
classvar = dr("Class")
hometownvar = dr("Hometown")
html.Append("<tr>")
Do While x < 4
html.Append("<td><p>" & namevar & "<br /> Hometown: " & hometownvar & "<br /> Class: " & classvar & "</p></td>")
x = x + 1
Loop
html.Append("</tr>")
x = 0
Loop
html.Append("</table>")
dr.Close()
conn.Close()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
brothersgird()
'write to panel maybe with this idea:
seniorpanel.html=html ???
End Sub
aspx side:
<asp:Panel ID="seniorpanel" runat="server">
</asp:Panel>
in your markup:
<asp:Panel ID="seniorpanel" runat="server">
<asp:GridView ID="brothersgird" runat="server" ShowHeader="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<p>
<%# Eval("Name")%><br />
Hometown:
<%# Eval("Hometown")%><br />
Class:
<%# Eval("Hometown")%>
</p>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
code-behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
brothersgird.DataSource = SelectBrothers()
brothersgird.DataBind()
End If
End Sub
Private Function SelectBrothers() As DataTable
Dim sql As String = "select Name, Hometown, Picture, Class from brothers"
Dim connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=~/App_Data/Members.accdb;Persist Security Info=False;"
Dim conn As New OleDbConnection(connstring)
Dim ds As New DataSet
Dim adapter As New OleDbDataAdapter()
adapter.SelectCommand = New OleDbCommand(sql, conn)
adapter.Fill(ds)
Return ds.Tables(0)
End Function
You familiar with DataGrids?
Client Side:
<asp:DataGrid runat="server" id="dataTable">
</asp:DataGrid>
Server Side:
//Get your data table from the database - let's say the variable is called dt
dataTable.DataSource = dt
dataTable.DataBind()
There is a lot more you can do with datagrids, but this should be enough to get you started if you decide to go this route.
Are you asking how to do this in javascript if you already have the data? If so an example would be kinda like this:
var row = document.createElement("TR");
var th1 = document.createElement("TH");
row.appendChild(th1);

Resources