ASP.NET VB Dropdown List - asp.net

ASP.NET dropdown populates correct items, but VB will not receive selected item. Not sure where to go from here. Could you please tell me why this is not occurring and how to resolve. I need to pass the selected item as a variable to the vb script.
ASP.NET:
<asp:DropDownList ID="ddlFacultyAssign" runat="server"
DataSourceID="FacultyAssign" Visible="false"
DataTextField="FULLNAME" DataValueField="FULLNAME"></asp:DropDownList>
<asp:SqlDataSource ID="FacultyAssign" runat="server"
ConnectionString="<%$ ConnectionStrings:nameOfString %>"
SelectCommand="EXEC SOCC.dbo.sp_util_FacultyAssign #PEOPLE_CODE_ID">
<SelectParameters>
<asp:QueryStringParameter Name="PEOPLE_CODE_ID" QueryStringField="USER" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
VB
Partial Public Class NotesContact
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.TextBox1.Text = Context.User.Identity.Name
Me.Calendar1.SelectedDate = DateTime.Today
If (Not IsPostBack) Then
ViewState("RefUrl") = Request.UrlReferrer.ToString()
End If
End Sub
Private Sub SAVE_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SAVE.Click
Dim MyConnection As SqlConnection
Dim MyCommand As SqlCommand
'Create a connection to the SQL Server.
MyConnection = New SqlConnection("server=**************************")
MyCommand = New SqlCommand("myStoredProcedure", MyConnection)
'Set the command type as StoredProcedure.
MyCommand.CommandType = CommandType.StoredProcedure
MyCommand.Parameters.Add(New SqlParameter("#FACASSIGN", SqlDbType.VarChar, 200))
MyCommand.Parameters("#FACASSIGN").Value = Me.ddlFacultyAssign.SelectedItem.Text
'Open and execute the statement
MyCommand.Connection.Open()
MyCommand.ExecuteNonQuery()
MyConnection.Close() 'Close the connection
GridView1.DataBind()

I'm pretty sure you want to use
Me.ddlFacultyAssign.SelectedValue

Have you tried doing this?
MyCommand.Parameters("#FACASSIGN").Value =
Me.ddlFacultyAssign.Items.Item(Me.ddlFacultyAssign.SelectedIndex).Text.Trim
And have you considered putting your dropdownlist and gridview in an update panel?

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 automatically select a file to FileUpload on page load?

I want to automatically select a file on page load to my FileUpload1. I tried searching but I cant find any related instances. I want to do somethhing like this.
Private Sub WebForm1_Load(sender As Object, e As EventArgs) Handles Me.Load
FileUpload1.setfile("D:\file\Test.Wav")
End Sub
Because my program is to record a sound (wav file) and it saves to a specific folder. And afterwards, I can select the recorded file and upload/save the file to the database.
When you click button_1, it records a sound using the mic. Then you will button_2 to stop and save the recorded sound.
But what i wanted to do is after clicking the button_2, it will stop and save the recording AND asynchronously it uploads the file to the database.
Here is the code: .VB file
Imports System.Data.SqlClient
Imports System.IO
Imports Microsoft.VisualBasic.Devices
Imports Microsoft.VisualBasic
Imports System.Runtime.InteropServices
Imports System.Text
Partial Class Default2
Inherits System.Web.UI.Page
Protected Sub btnUpload_Click(sender As Object, e As EventArgs) Handles btnUpload.Click
Using br As New BinaryReader(FileUpload1.PostedFile.InputStream)
Dim bytes As Byte() = br.ReadBytes(CInt(FileUpload1.PostedFile.InputStream.Length))
Dim strConnString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(strConnString)
Using cmd As New SqlCommand()
cmd.CommandText = "insert into tblFiles(Name, ContentType, Data) values (#Name, #ContentType, #Data)"
cmd.Parameters.AddWithValue("#Name", Path.GetFileName(FileUpload1.PostedFile.FileName))
cmd.Parameters.AddWithValue("#ContentType", "audio/mpeg3")
cmd.Parameters.AddWithValue("#Data", bytes)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Using
Response.Redirect(Request.Url.AbsoluteUri)
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim strConnString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(strConnString)
Using cmd As New SqlCommand()
cmd.CommandText = "select Id, Name from tblFiles"
cmd.Connection = con
con.Open()
GridView1.DataSource = cmd.ExecuteReader()
GridView1.DataBind()
con.Close()
End Using
End Using
End Sub
<DllImport("winmm.dll")> _
Private Shared Function mciSendString(ByVal command As String, ByVal buffer As StringBuilder, ByVal bufferSize As Integer, ByVal hwndCallback As IntPtr) As Integer
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim i As Integer
i = mciSendString("open new type waveaudio alias capture", Nothing, 0, 0)
i = mciSendString("record capture", Nothing, 0, 0)
Label1.Text = "Recording"
Label1.BackColor = Drawing.Color.Green
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Try
Dim i As Integer
i = mciSendString("save capture " & "D:\file\Test.Wav", Nothing, 0, 0)
i = mciSendString("close capture", Nothing, 0, 0)
Label1.Text = "Idle"
Label1.BackColor = Drawing.Color.Yellow
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub WebForm1_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class
aspx.file
<form runat="server">
<asp:Button ID="Button1" runat="server" Text="Record" />
<asp:Button ID="Button2" runat="server" Text="Save" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload"
onclick="btnUpload_Click" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" RowStyle- BackColor="#A1DCF2" Font-Names = "Arial" Font-Size = "10pt"
HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White">
<Columns>
<asp:BoundField DataField="Name" HeaderText="FileName" />
<asp:TemplateField>
<ItemTemplate>
<object type="application/x-shockwave-flash" data='dewplayer-vol.swf?mp3=File.ashx?Id=<%# Eval("Id") %>'
width="240" height="20" id="dewplayer">
<param name="wmode" value="transparent" />
<param name="movie" value='dewplayer-vol.swf?mp3=File.ashx?Id=<%# Eval("Id") %>'/>
<object>
</ItemTemplate>
</asp:TemplateField>
<asp:HyperLinkField DataNavigateUrlFields="Id" Text = "Download" DataNavigateUrlFormatString = "~/File.ashx?Id={0}" HeaderText="Download" />
</Columns>
</asp:GridView>
I don't think it is possible due to security reasons. Imagine you visit a random site and it automatically starts uploading files from your local file system without your knowledge/permission.
The input type file control requires the user to select a file to upload, so there is no way you can do it programmatically.

How to set a nested datasource from code behind?

Connection String (Conn) is set globally on page load.
(As below. I use this for all sqldatasources and it work perfectly.)
VB.NET (Page Load)
Imports Connections
Dim Conn As New System.Data.SqlClient.SqlConnection
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Conn.ConnectionString = ConfigurationManager.ConnectionStrings(StringConn).ConnectionString
sqlRepeater.ConnectionString = Conn.ConnectionString
End Sub
How to set a nested datasource from code behind?
I have a nested gridview inside a repeater and am trying to set the sqldatasource's connectionstring on itemdatabound instead of page load. (As below.)
VB.NET (Repeater Item Databound)
Protected Sub rpt_ItemDataBound(ByVal sender As Object, ByVal e As RepeaterItemEventArgs) Handles rpt.ItemDataBound
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
Dim sqlGridview As SqlDataSource = DirectCast(e.Item.FindControl("sqlGridview"), SqlDataSource)
sqlGridview.ConnectionString = Conn.ConnectionString
End If
End Sub
ASPX
<asp:Repeater ID="rpt" runat="Server" DataSourceID="sqlRepeater">
<ItemTemplate>
<asp:GridView ID="gv" runat="Server" AutoGenerateColumns="False" DataSourceID="sqlGridview">
...
</GridView>
<asp:SqlDataSource ID="sqlGridview" runat="Server" SelectCommand="sp" SelectCommandType="StoredProcedure"/>
</ItemTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="sqlRepeater" runat="Server" SelectCommand="sp" SelectCommandType="StoredProcedure"/>
This code outputs error:
The ConnectionString property has not been initialized.
TRIED TO CREATE FUNCTION TO PASS IN THE CONNECTION STRING
ASPX
Replaceed above sqlsource with this to call function
<asp:SqlDataSource ID="sqlGridview" runat="Server" SelectCommand="sp" SelectCommandType="StoredProcedure" ConnectionString='<%# GetConnectionString()%>'/>
VB.NET
Protected Function GetConnectionString() As String
Dim Conn As New System.Data.SqlClient.SqlConnection
Conn.ConnectionString = ConfigurationManager.ConnectionStrings(StringConn).ConnectionString
Return Conn.ConnectionString
End Function
This is just an idea, but the problem might be the fact that by the time ItemDataBound is called GridView's data binding is already done, or was attempted to be done. And during this attempt a connection string was not set indeed.
To correct that you might want to do two things. First - set connection string in markup, so that data source has it before data binding is done. Something like this:
<asp:SqlDataSource ID="sqlGridview" runat="Server"
ConnectionString='<%# GetConnectionString(); %>' ... />
Where GetConnectionString is a protected method in code behind that just returns the
connection string:
Protected Function GetConnectionString() As String
Return Conn.ConnectionString
End Function
Of course that means that there is no need to handle ItemDataBound anymore, unless you were doing something else there as well.
Second - reverse the order of controls inside the item template. This most likely is not necessary, but I am not entirely sure about an exact time when the GridView will be data bound, so this will help to ascertain that connection string is set:
<ItemTemplate>
<asp:SqlDataSource ID="sqlGridview" runat="Server"
<asp:GridView ID="gv" runat="Server" ...
</ItemTemplate>
In Your Class Library
Use this to cast initially the sqlConnection then execute the connection when using it.
Public Class MyLibrary
'-------------------SQL Database Variables----------------
Dim SerialMACDatabase As String = Nothing
Dim SerialMac As SqlConnection
Dim CMD As New SqlCommand
Dim sqlAdapter As SqlDataAdapter
Public Sub New(ByVal lserialMACDatabase As String)
SerialMACDatabase = lserialMACDatabase
End Sub
Private Sub connectToDB()
Try
SerialMac = New SqlConnection(SerialMACDatabase)
SerialMac.Open()
Catch ex As Exception
End Try
End Sub
Public Sub issueCommand(ByVal sQuery As String)
Try
connectToDB()
CMD = New SqlCommand(sQuery, TestResult)
CMD.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Libraryy As New MyLibrary(strSQLCONNECTION)
Libraryy.IssueCommand("INSERT SOMETHING")
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.

Resources