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.
Related
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?
I've got a legacy VB.Net app that I'm modifying in VS 2010; here's the relevant code:
<form id="form1" runat="server">
<asp:GridView ID="gvCommentsEdit" runat="server" ShowHeader="False">
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
*** On
<asp:Label ID="lblTimestamp" runat="server" Text='<%# Bind("comment_date") %>'></asp:Label>
<asp:Label ID="lblUpdateBy" runat="server" Text='<%# Bind("update_by") %>'></asp:Label> commented:<br />
<asp:TextBox ID="txtEditCommentPopup" runat="server" Columns="55" Rows="10" Text='<%# bind("text") %>' TextMode="MultiLine"></asp:TextBox>
<asp:LinkButton ID="lnkSaveComment" runat="server" OnClick="lnkSaveComment_Click">Save</asp:LinkButton>
<asp:LinkButton ID="lnkCancelEdit" runat="server" OnClick="lnkCancelEdit_Click">Cancel</asp:LinkButton>
<asp:HiddenField ID="hdnCommentID" Value='<%# Bind("comment_id") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
Code Behind is:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim IdNumber As Integer = sender.ClientQueryString
Dim mydata As New Profile_Data
gvCommentsEdit.DataSource = mydata.returnCommentsById(RequestedUsername, IdNumber)
gvCommentsEdit.DataBind()
End Sub
Sub lnkSaveComment_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim myRow = sender.parent
Dim mydata As New Profile_Data
Dim IdNumber As String = CType(myRow.FindControl("hdnCommentID"), HiddenField).Value
Dim text As String = CType(myRow.FindControl("txtEditCommentPopup"), TextBox).Text
mydata.UpdateComment(IdNumber, text)
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "CloseWindowScript", "window.opener.location.href = window.opener.location;window.close();", True)
End Sub
End Class
This page is a popup from the main page and populates fine. The problem is when I change the txtEditCommentPopup TextBox, which then calls lnkSaveComment_Click(), it has the original textbox values, not the changed value. I'm not using AutoPostBack. Any ideas on why? Thanks!
Assuming the database update is working correctly, the problem is that you are binding the GridView on every PostBack, but not after the data is updated.
When you click your button, you should see that your Page_Load method is called, your GridView is bound, then your lnkSaveComment_Click method is called, updating the database. But afterwards, you are not rebinding with the new data.
So my guess is that if you were to click the update button again (or cause another PostBack somehow), your new data would show up.
The fix would be to make sure you bind your GridView again after you update the data.
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
Sub lnkSaveComment_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim myRow = sender.parent
Dim mydata As New Profile_Data
Dim IdNumber As String = CType(myRow.FindControl("hdnCommentID"), HiddenField).Value
Dim text As String = CType(myRow.FindControl("txtEditCommentPopup"), TextBox).Text
mydata.UpdateComment(IdNumber, text)
BindGridView()
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "CloseWindowScript", "window.opener.location.href = window.opener.location;window.close();", True)
End Sub
Sub BindGridView()
Dim IdNumber As Integer = Page.ClientQueryString
Dim mydata As New Profile_Data
gvCommentsEdit.DataSource = mydata.returnCommentsById(RequestedUsername, IdNumber)
gvCommentsEdit.DataBind()
End Sub
I added this in your page load
If Not IsPostBack Then
'your code
End If
so replace your Page_Load with this:-
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Dim IdNumber As Integer = sender.ClientQueryString
Dim mydata As New Profile_Data
gvCommentsEdit.DataSource = mydata.returnCommentsById(RequestedUsername, IdNumber)
gvCommentsEdit.DataBind()
End If
End Sub
Hope this will help you.
I have a Windows form with 1 DataGrid which has a Dropdownlist in one of its columns.
I also have another dropDownlist outside of this DataGrid.
Both of these dropdowns are bound to same dataset and both get populated with same items.
Both of DropDowns have their Autopostbacks set to true.
Problem is only for the dropdownlist Outside of Datagrid SelectedIndexChange Event gets fired:
(I have seen multiple similar questions on SO but none of suggestions works for me. So I really appreciate if you can help me here.
)
Protected Sub ABCD(ByVal sender As System.Object, ByVal e As System.EventArgs)
End Sub
For both Dropdownlists: AutoPostBack="True"
Here is Vb code:
Imports System.Data.OleDb
Public Class WebForm1
Inherits System.Web.UI.Page
Protected WithEvents dg As New System.Web.UI.WebControls.DataGrid
Private cnDB As New OleDbConnection
Private ds As New DataSet
Private daDB As New OleDbDataAdapter
Protected allNames As New DataSet
Protected MyDataSet As DataSet
Protected WithEvents DropDownList1 As System.Web.UI.WebControls.DropDownList
Protected WithEvents DropDownList2 As System.Web.UI.WebControls.DropDownList
Protected WithEvents ddlName As New System.Web.UI.WebControls.DropDownList
#Region " Web Form Designer Generated Code "
'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
End Sub
'NOTE: The following placeholder declaration is required by the Web Form Designer.
'Do not delete or move it.
Private designerPlaceholderDeclaration As System.Object
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub
#End Region
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
MyDataSet = NameBudget()
GridDataLoad()
End Sub
Protected Sub Grid_EditCommand(ByVal source As Object, ByVal e As DataGridCommandEventArgs)
dg.EditItemIndex = e.Item.ItemIndex
dg.DataSource = ds
dg.DataBind()
End Sub
Protected Sub Grid_CancelCommand(ByVal source As Object, ByVal e As DataGridCommandEventArgs)
dg.DataSource = ds.Tables(0).DefaultView
dg.EditItemIndex = -1
dg.DataSource = ds
dg.DataBind()
End Sub
Protected Sub Grid_UpdateCommand(ByVal source As Object, ByVal e As DataGridCommandEventArgs)
End Sub
Private Function GridDataLoad()
ddlName.DataSource = MyDataSet
Dim i As Object = MyDataSet.Tables(0)
ddlName.DataBind()
DropDownList1.DataSource = MyDataSet
DropDownList1.DataBind()
Dim strCon As String = _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\AccessTestDataBases\TestDB.mdb; "
Dim cnDB As New OleDbConnection(strCon)
cnDB.Open()
daDB = New OleDbDataAdapter("Select * from [Persons]", cnDB)
daDB.Fill(ds, "tbl1")
Dim j As Object = ds.Tables(0)
dg.DataSource = ds
dg.DataBind()
cnDB.Close()
Dim ii As Object = ds.Tables(0)
End Function
Protected Function NameEditable(ByVal n As String) As Boolean
Return True
End Function
Protected Function NameBudget() As DataSet
Dim strCon As String = _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\AccessTestDataBases\TestDB.mdb; "
Dim cnDB As New OleDbConnection(strCon)
cnDB.Open()
daDB = New OleDbDataAdapter("Select ID,Name from [Persons]", cnDB)
Dim ds As New DataSet
daDB.Fill(ds, "tbl1")
cnDB.Close()
Return ds
End Function
Sub SetDefaultListItem(ByVal sender As Object, ByVal e As System.EventArgs)
'*************************************************************************
'* Use this sub to set the Default List for DropDown Listboxes *
'*************************************************************************
Try
If Len(sender.DefaultValue) > 0 Then
If sender.Items.FindByValue(sender.DefaultValue).ToString.Length > 0 Then
sender.Items.FindByValue(sender.DefaultValue).Selected = True
End If
End If
Catch ex As System.Exception
'Throw New System.Exception(ex.ToString())
End Try
End Sub
Protected Sub ABCD(ByVal sender As System.Object, ByVal e As System.EventArgs)
End Sub
End Class
Here is the HTML for datagrid and Dropdownlists:
<Columns>
<ASP:ButtonColumn Text="Delete" CommandName="Delete"></ASP:ButtonColumn>
<asp:EditCommandColumn ButtonType="LinkButton" UpdateText="Update" CancelText="Cancel"
EditText="Edit"></asp:EditCommandColumn>
<ASP:TemplateColumn HeaderText="Name" SortExpression="FY" HeaderStyle-HorizontalAlign="center" HeaderStyle-Wrap="True">
<ItemStyle Wrap="false" HorizontalAlign="left" />
<ItemTemplate>
<ASP:Label ID="Name" Text='<%# DataBinder.Eval(Container.DataItem, "Name") %>' runat="server"/>
</ItemTemplate>
<EditItemTemplate>
<ASP:DropDownList id="DropDownlist2" datasource="<%# MyDataSet %>" DataTextField= "Name" DataValueField="ID" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ABCD">
</ASP:DropDownList>
</EditItemTemplate>
</ASP:TemplateColumn>
</Columns>
<asp:DropDownList id="DropDownList1"
datasource="<%# MyDataSet %>" DataTextField= "Name"
DataValueField="ID" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="ABCD">
</asp:DropDownList>
I am attempting to sort a gridview in an updatepanel. It compiles, but I get an Object reverence not set to an instance of an object error. I am trying to follow this guide, but in vb
default.aspx
<ajx:UpdatePanel ID="ajaxpanel" runat="server">
<ContentTemplate>
<asp:GridView ID="gvProgramDetails" runat="server" AutoGenerateColumns="False"
CssClass="gridview" DataKeyNames="ProgramNumber"
AllowPaging="True" PageSize="2" AllowSorting="True" OnSorting="gvProgramDetails_Sorting">
<Columns>
<asp:CommandField ControlStyle-CssClass="button delete" ShowDeleteButton="True">
<ControlStyle CssClass="button delete" />
</asp:CommandField>
<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"
SortExpression="ProgramName" />
<asp:BoundField DataField="ProgramStatus" HeaderText="ProgramStatus"
SortExpression="ProgramStatus" />
<asp:BoundField DataField="RecordType" HeaderText="RecordType"
SortExpression="RecordType" />
<asp:BoundField DataField="ProgramInformation" HeaderText="ProgramInformation"
SortExpression="ProgramInformation" />
</Columns>
</asp:GridView>
</ContentTemplate>
default.aspx.vb
Imports System.Web.Services
Partial Class processes_ProgramTrack_Default
Public Property SortOrder() As String
Get
If (ViewState("SortOrder").ToString = "desc") Then
ViewState("SortOrder") = "asc;"
Else
ViewState("SortOrder") = "desc"
End If
Return ViewState("SortOrder").ToString()
End Get
Set(ByVal value As String)
ViewState("SortOrder") = value
End Set
End Property
Public Sub bindGridView(Optional ByVal sortExp As String = "", Optional ByVal sortDir As String = "")
Dim connstr As String = ConfigurationManager.ConnectionStrings("WEBConnectionString").ConnectionString
Dim conn As New SqlConnection(connstr)
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim myDataView As New DataView()
Dim mysqlCommand As New SqlCommand("SELECT tblPrgTrackPrograms.ProgramNumber, tblPrgTrackPrograms.ProgramName, tblPrgTrackPrograms.ProgramStatus, tblPrgTrackProgramDocumentation.RecordType, tblPrgTrackProgramDocumentation.ProgramInformation FROM tblPrgTrackPrograms INNER JOIN tblPrgTrackProgramDocumentation ON tblPrgTrackPrograms.ProgramNumber = tblPrgTrackProgramDocumentation.ProgramNumber")
Dim myDataSet As New DataSet()
Dim mySQLAdapter As New SqlDataAdapter(mysqlCommand)
mySQLAdapter.SelectCommand.Connection = conn
mySQLAdapter.Fill(myDataSet)
myDataView = myDataSet.Tables(0).DefaultView
If sortExp <> String.Empty Then
myDataView.Sort = String.Format("{0}{1}", sortExp, sortDir)
End If
gvProgramDetails.DataSource = myDataView
gvProgramDetails.DataBind()
End Sub
Protected Sub gvProgramDetails_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvProgramDetails.Load
bindGridView()
End Sub
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
Protected Sub gvProgramDetails_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles gvProgramDetails.RowDeleting
End Sub
Protected Sub gvProgramDetails_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles gvProgramDetails.Sorting
SortOrder = ViewState("SortOrder").ToString
bindGridView(e.SortExpression, SortOrder)
End Sub
End Class
I get the error message as a popup msgbox. What I think is happening, SortOrder isn't getting assigned a value.
You need to make sure that you ViewState("SortOrder") has a value in it before you try to call ToString. Otherwise, it will throw that exception (as you've seen) because you cannot call the ToString method on null.
Essentially, you need to wrap your references to that ViewState variable in a "If (ViewState("SortOrder") IsNot Nothing Then" block, and possibly provide special handling in the "Else" section (if you need that).
Something like this for your property:
Public Property SortOrder() As String
Get
If (ViewState("SortOrder") IsNot Nothing Then
If (ViewState("SortOrder").ToString = "desc") Then
ViewState("SortOrder") = "asc;"
Else
ViewState("SortOrder") = "desc"
End If
End If
Return ViewState("SortOrder").ToString()
End Get
Set(ByVal value As String)
ViewState("SortOrder") = value
End Set
End Property
And then the same thing for your sorting event:
Protected Sub gvProgramDetails_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles gvProgramDetails.Sorting
If (ViewState("SortOrder") IsNot Nothing Then
SortOrder = ViewState("SortOrder").ToString
bindGridView(e.SortExpression, SortOrder)
End If
End Sub
Note: This is my best guess at your problem, given the information you've provided so far. If you provide the line that's throwing the error, I'd be glad to take another look.
I'm new to asp.net and have recently been working with creating a GridView from codebehind to make it more flexible so that I can eventually have it created based on user specifications.
Now I'm exploring classes, and I thought it would be cool to create a GridView class so that whenever I need to make a GridView I can just pass the class my specifications instead of having the same code re-written on each page's codebehind.
I'm not really seeing too many examples of how to accomplish this though. Have any of you done this? Does it even make sense for me to do this?
Here's how I'm currently making my GridView with codebehind. Any idea how I can change this to create the GridView with a class?
.aspx page:
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False"
EmptyDataText="There are no data records to display." AllowPaging="True"
CssClass="GridViewStyle" GridLines="None" Width="100%">
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="EmployeeID"
DataNavigateUrlFormatString="EmployeeProfile.aspx?EmployeeID={0}"
DataTextField="EmployeeID"
DataTextFormatString= "<img src='Images/icons/document-search-result.png' alt='View'/> <u>View</u>" >
<ControlStyle CssClass="titleLinksB" />
<ItemStyle Wrap="False" />
</asp:HyperLinkField>
</Columns>
<RowStyle CssClass="RowStyle" />
<EmptyDataRowStyle CssClass="EmptyRowStyle" />
<PagerSettings Mode="NumericFirstLast" PageButtonCount="5" />
<PagerStyle CssClass="PagerStyle" />
<SelectedRowStyle CssClass="SelectedRowStyle" />
<HeaderStyle CssClass="HeaderStyle" />
<EditRowStyle CssClass="EditRowStyle" />
<AlternatingRowStyle CssClass="AltRowStyle" />
<SortedAscendingHeaderStyle CssClass="sortasc"></SortedAscendingHeaderStyle>
<SortedDescendingHeaderStyle CssClass="sortdesc"></SortedDescendingHeaderStyle>
</asp:GridView>
.aspx.vb Code-behind page:
Partial Class GridTest2
Inherits System.Web.UI.Page
Sub Page_load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
CreateGridColumns()
BindGrid()
End If
End Sub
Public Property SortExpression As String
Get
If ViewState("SortExpression") Is Nothing Then
ViewState("SortExpression") = "LastName ASC"
End If
Return ViewState("SortExpression").ToString
End Get
Set(ByVal value As String)
ViewState("SortExpression") = value
End Set
End Property
Private Sub CreateGridColumns()
Dim curLastName As New BoundField
curLastName.HeaderText = "Last Name"
curLastName.DataField = "LastName"
curLastName.SortExpression = "LastName"
GridView1.Columns.Insert(0, curLastName)
Dim curFirstName As New BoundField
curFirstName.HeaderText = "First Name"
curFirstName.DataField = "FirstName"
curFirstName.SortExpression = "FirstName"
GridView1.Columns.Insert(1, curFirstName)
End Sub
Private Sub BindGrid()
Try
Dim tblData = New DataTable
Using sqlCon As New SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("dbConnectionString").ConnectionString.ToString())
Dim sql As String = "SELECT * FROM Employees"
Dim sqlCmd = New SqlClient.SqlCommand()
sqlCmd.CommandText = String.Format(sql, Me.SortExpression)
sqlCmd.Connection = sqlCon
Using objAdapter As New SqlClient.SqlDataAdapter(sqlCmd)
objAdapter.Fill(tblData)
End Using
End Using
GridView1.DataSource = tblData
GridView1.DataBind()
GridView1.HeaderRow.CssClass = "HeaderStyle"
Catch ex As Exception
' TODO: log error '
Throw
End Try
End Sub
Private Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView1.PageIndexChanging
Me.GridView1.PageIndex = e.NewPageIndex
BindGrid()
End Sub
Protected Sub GridView1_RowDataBound1(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
'Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Dim gridView As GridView = DirectCast(sender, GridView)
Dim sortColumn As String, sortDirection As String
sortColumn = Me.SortExpression.Split(" "c)(0)
sortDirection = Me.SortExpression.Split(" "c)(1)
If e.Row.RowType = DataControlRowType.Header Then
Dim cellIndex As Integer = -1
For Each field As DataControlField In gridView.Columns
If field.SortExpression = sortColumn Then
cellIndex = gridView.Columns.IndexOf(field)
End If
Next
If cellIndex > -1 Then
' this is a header row, set the sort style
e.Row.Cells(cellIndex).CssClass = If(sortDirection = "ASC", "sortasc", "sortdesc")
End If
End If
End Sub
Private Sub GridView1_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles GridView1.Sorting
Dim currentSortColumn, currentSortDirection As String
currentSortColumn = Me.SortExpression.Split(" "c)(0)
currentSortDirection = Me.SortExpression.Split(" "c)(1)
If e.SortExpression.Equals(currentSortColumn) Then
' switch sort direction '
Select Case currentSortDirection.ToUpper
Case "ASC"
Me.SortExpression = currentSortColumn & " DESC"
Case "DESC"
Me.SortExpression = currentSortColumn & " ASC"
End Select
Else
Me.SortExpression = e.SortExpression & " ASC"
End If
BindGrid()
End Sub
End Class
Any help is greatly appreciated!
If i understand correctly you are trying to make Custom Gridview class. you can follow below links for your help. All you need to do is make a class which inherits Gridview class so that you override default functionality to make it more generic.
Extending the GridView Control
Custom Gridview with paging and filtering
Creating Custom Gridview Control