I'm usually a PHP guy but got stuck doing a project in vb.net.
I have a query (sqldatasource) that returns a single value (the last update date).
I want to use a label to say something like "Last updated: " < Label = (returned value) >
In PHP this would be simple. In vb.net, all I can find are endless badly written code behinds showing how you'd execute the query onLoad then bind it to the label.
Is this really the only way to do this? It seems like a ridiculously simple problem to have such a long solution. I have used a datagrid control to just bind the query result directly, but it prints the column name as well as the date, so it's not ideal.
Any ideas?
In your Page_Load method, run your query. On your page.aspx, you have a form control, lets call it label1. Set label1.text = queryResult.
Sub Page_Load()
dim myConnection as new data.sqlclient.sqlconnection
dim myCommand as new data.sqlclient.sqlcommand
dim sqlReader as data.sqlclient.sqldatareader
myConnection.connectionString = 'enter your connection string details'
myConnection.Open()
myCommand = New SqlCommand("Select lastUpdated from yourTable", myConnection)
sqlReader = myCommand.ExecuteReader()
if sqlReader.hasRows then
sqlReader.read()
label1.text = Format("MM/dd/yyyy", sqlReader("lastUpdated"))
end if
End Sub
And your page.aspx (somewhere)
<asp:label id="Label1" runat="server" />
PS - I may be off on the format function above, been awhile.
EDIT based on user comment:
Well, for what you are doing, I wouldn't really recommend a SQLDataSource as it is really meant to be bound to a control such as a gridview or repeater. However, if you want to use the SQLDataSource, you will need to bind to a DataView in your code-behind. From there, you can access each row (you should only have one) and column by name.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim dv As New Data.DataView
'use the id of your SqlDataSource below'
dv = SqlDataSource1.Select(DataSourceSelectArguments.Empty)
Label1.Text = dv.Table.Rows(0)("LastUpdated")
End Sub
TO use a connection string from the web.config:
Web.Config File:
<appSettings>
<add key="strConnectionString" value="Data Source=192.168.0.55;Database=Times;User ID=sa;PassWord=sa"/>
</appSettings>
Code Behind:
Dim sqlConn as new data.sqlClient.SqlConnection()
sqlConn.ConnectionString=ConfigurationManager.ConnectionStrings("strConnectionString").ConnectionString
sqlConn.Open()
Related
I am using a GridView in ASP.NET and am building it up programmatically. However, when I go to sort, I am getting an error thrown because the event is not being handled correctly.
I've not worked with ASP.NET GridViews in a long time and am extremely rusty on this one.
This is the code I have so far:
Public Sub GetData()
Using sqlConn As New SqlConnection(_connstr)
Dim sqlcmd As New SqlCommand()
sqlcmd.Connection = sqlConn
sqlcmd.CommandType = CommandType.StoredProcedure
sqlcmd.CommandText = "dbo.uspGetEmailAudit"
sqlcmd.Parameters.Add(requestIdParam)
Using sqlda As New SqlDataAdapter(sqlcmd)
sqlda.Fill(_dt)
End Using
End Using
BindData(_dt)
End Sub
Private Sub BindData(dt As DataTable)
GridView1.DataSource = _dt
GridView1.AllowSorting = True
GridView1.AllowPaging = True
GridView1.PageSize = 15
GridView1.DataBind()
End Sub
Protected Sub sorting(sender As Object, e As GridViewSortEventArgs)
ViewState("sortexp") = e.SortExpression
GridView1.DataSource = GetData()
GridView1.DataBind()
End Sub
The error that I am getting is:
The GridView 'GridView1' fired event Sorting which wasn't handled.
Somewhere in Form_Load or otherwise, you need to wire up the OnSorting event.
Examples are here:
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting(v=vs.110).aspx
In your GridView markup, tell it to use your sub:
<asp:GridView runat="server" OnSorting="sorting" id="GridView1" />
You have to wire it up, it won't do it for you.
If you create the GridView in code, you'll need to do the VB.NET equivalent of this C# code (sorry, I'm not a VB guy)
GridView1.OnSorting += sorted;
I have an asp.net Visual Basic web site, and I am using a stored procedure to get values to populate a drop-down list.
However, I have two issues. If I put the method to fill the drop-down list within my If Not IsPostBack statement in the page load event, then the whole list is filled with items saying 'System.Data.DataViewRow' instead of the actual values. If I put it outside this 'if' statement but still in my page load event, I get the correct values, but no matter what I select, when I leave the drop-down it reverts back to the top item instead of the selected item.
What am I doing wrong??
Edit: I have now added the DataTextField as suggested by Nic and put the method inside my 'If Not IsPostBack' event as suggested by Lee Bailey. However, my drop-down is still showing all values as 'System.Data.DataViewRow' so I don't know if Lee's solution has worked or not! Any other ideas on the issue of showing the values! I have updated my code below to reflect the changes.
The visual basic:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
bodyPanel.Visible = False
drpRegion_fill()
End If
End Sub
Protected Sub drpRegion_fill()
Dim sqlConn As SqlConnection
sqlConn = New SqlConnection
sqlConn.ConnectionString = ConfigurationManager.ConnectionStrings("ConnString").ConnectionString
Dim drpRegionCmd As SqlCommand
drpRegionCmd = New SqlCommand("getRegionName", sqlConn)
drpRegionCmd.CommandType = CommandType.StoredProcedure
Dim drpRegionAdp As SqlDataAdapter
drpRegionAdp = New SqlDataAdapter(drpRegionCmd)
Dim drpRegionDs As DataSet
drpRegionDs = New DataSet
sqlConn.Open()
drpRegionAdp.Fill(drpRegionDs)
With drpRegion
.DataSource = drpRegionDs
.DataBind()
.DataValueField = "regionName"
.DataTextField = "regionName"
.SelectedIndex = 0
End With
sqlConn.Close()
End Sub
The markup:
<asp:Panel ID="panelRegion" runat="server" Height="160px" Width="71%" CssClass="inlineBlock">
<h2>Region:</h2>
<asp:dropDownList runat="server" AutoPostBack="true" ID="drpRegion" />
</asp:Panel>
The SQL procedure returns a two-column dataset with 'regionID' as column 1, and 'regionName' as column2.
I've spent about two days on this now, trying various things and reading all the books I can! I have never had this issue in C# when I have performed the same operation and I cannot for the life of me think what I've missed in the VB...
It does not look as though you are setting the DataTextField property of your DropDownList:
With drpRegion
.DataSource = drpRegionDs
.DataValueField = "regionName"
.DataTextField = "fieldToDisplayAsText"
.SelectedIndex = 0
.DataBind()
End With
source:
MSDN DataTextField
It's reverting back to the original value because you are re-binding the values to the dropdown after a postback. Changing the selected item is triggering a postback because you have the AutoPostBack property set to true. I would call drpRegion_fill() only if it's not a postback. Setting the DataTextField as Ric mentioned should solve the problem regarding 'System.Data.DataViewRow'
I have searched everywhere to understand this procedure but nothing has worked so far.
Basically what i want is to link my dropdownlist which is ddlreportid to various textboxes.
Currently, the drop down list is connected to a datasource where it is using the report table to show a list of reportid's e.g 1, 2,3, etc.
What I want to happen is if a user clicks on, say, 1 from the ddlreportid. I want reportname to be placed into txtreportname.text textbox, reportaddress to be placed into txtreportaddress textbox and reportpostcode to be paced into txtreportpostcodec textbox.
Where do I start? If soemone could direct me that would be great.
I have used this code previously but its not working.
Protected Sub ddlreportid_SelectedIndexChanged1(sender As Object, e As System.EventArgs) Handles ddlreportid.SelectedIndexChanged
Dim myConn As New SqlConnection
Dim myCmd As New SqlCommand
myConn.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
myCmd = myConn.CreateCommand
myCmd.CommandText = "SELECT ReportName, ReportAddress, ReportPostcode WHERE ReportID = # ReportID"
myCmd.Parameters.Add(New SqlParameter("#ReportID", (ddlreportid.Text)))
Dim reader As SqlDataReader = myCmd.ExecuteReader()
If (reader.Read()) Then
txtreportname.Text = reader(0)
txtreportaddress.Text = reader(1)
txtreportpostcode.Text = reader(2)
End If
myCmd.Dispose()
myConn.Close()
myConn.Dispose()
End Sub
Thank you
Try, instead of ...
myCmd.Parameters.Add(New SqlParameter("#ReportID", (ddlreportid.Text)))
... doing this:
myCmd.Parameters.Add(New SqlParameter("#ReportID", (ddlreportid.SelectedItem.Value)))
Also be sure your dropdownlist has AutoPostBack = "true" if you want your page to respond immediately.
Good afternoon people have been trying to fill a dropdown using a sql command, until so good, when I click on the dropdown it shows all the items, but when I try to click on an item in the dropdown it always returns the first item in the dropdown .... follows the codes, what i want to do is get the selected value and item from the dropdown and save it on a label for future use.
I appreciate all the support possible,
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
utilizador.Text = Me.Context.User.Identity.Name
If (Not Page.IsPostBack) Then
escolhePerfil()
End If
'DropDownPerfil.DataBind()
lbperfil2.Text = DropDownPerfil.SelectedItem.Text
lbnome.Text = DropDownPerfil.SelectedValue
End Sub
Function escolhePerfil() As Boolean
Dim connstring As String = "Data Source=10.2.24.17;Persist Security Info=True;User ID=sa;Password=Pr0dUn1C0$qL;database=ePrimavera"
Dim SQLData As New System.Data.SqlClient.SqlConnection(connstring)
Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT u.WindowsUser,u.Email ,g.Description, u.Login FROM [ePrimavera].[dbo].[PLT_Users] as u,[ePrimavera].[dbo].[PLT_UserGroups] as ug, [ePrimavera].[dbo].[PLT_Groups] as g where u.ID = ug.UserID And ug.GroupID = g.ID and u.WindowsUser like 'bancounico\" & utilizador.Text & "'", SQLData)
SQLData.Open()
Dim dtrReader As System.Data.SqlClient.SqlDataReader = cmdSelect.ExecuteReader()
If dtrReader.HasRows Then
DropDownPerfil.DataValueField = "Login"
DropDownPerfil.DataTextField = "Description"
DropDownPerfil.DataSource = dtrReader
DropDownPerfil.DataBind()
End If
SQLData.Close()
Return True
End Function
.aspx
<asp:DropDownList ID="DropDownPerfil" runat="server"
Height="16px" Width="202px" CssClass="DropBorderColor">
</asp:DropDownList>
try the following code:
Protected Sub DropDownPerfil_SelectedIndexChanged(sender As Object, e As EventArgs)
lbperfil2.Text = DropDownPerfil.SelectedItem.Text
lbnome.Text = DropDownPerfil.SelectedValue
End Sub
The problem is that you are trying to get the value "too early". The value is not valid in the Page_Load, since the control's OnLoad event fired after the Page's OnLoad (Page_Load) event.
The way, what the others wrote the correct, since the Event handlig section (inclueding control's onchanged event) will process after the Load section.
For more details check the offical ASP.NET life cycle site in the MSDN
The likely reason is that some (if not all) the values you are assigning to the DropDownList for Login are occur more than once.
When you then select an item in the DDL, if the value of that item occurs more than once, the selected index will highlight the first instance. To test this, comment out DropDownPerfil.DataValueField = "Login"
I am sure upon selection, it will highlight the correct item you intended on selecting.
When I click the "Update" button in the gridview, it fire the RowUpdating event, but it returns a error "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index"
The following is the vb code:
Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
If e.RowIndex >= 0 Then
Dim row As GridViewRow = DirectCast(Gridview1.Rows(e.RowIndex), GridViewRow)
Dim Col1_SL As CheckBox = DirectCast(row.FindControl("cb1_SL"), CheckBox)
.................
Dim cmd As New System.Data.SqlClient.SqlCommand
Dim sql As String
Dim reader As System.Data.SqlClient.SqlDataReader
Using conn As New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("hris_shiftdutyConnectionString").ConnectionString)
conn.Open()
cmd.Connection = conn
sql = "SET DATEFORMAT dmy;UPDATE troster SET SL='" & Convert.ToInt32(Col1_SL.Checked) & "' where roster_key='" & Col1_RosterKey.Text & "';"
cmd.CommandText = sql
reader = cmd.ExecuteReader()
conn.Close()
reader.Close()
End Using
'Reset the edit index.
Gridview1.EditIndex = -1
'Bind data to the GridView control.
BindData()
End If
End Sub
Please help. Thanks
Joe
Since the ViewState is disabled and you are only databinding when the page is not being posted back, this line is always going to fail:
Dim row As GridViewRow = DirectCast(Gridview1.Rows(e.RowIndex), GridViewRow)
as the count on Gridview1.Rows is going to be 0.
When the page is posted back to the server, ASP.NET needs the ViewState to be enabled for the control so it can recreate the controls and properly determine which events to raise, which control values have changed, etc. You should enable the ViewState, and you'll have to figure out what is causing the control tree error. There must be some other modification that is taking place in the code.
Keep in mind that only databinding the GridView in Page_Load when the page is not posted back is correct, but you won't be able to properly handle events unless you enable ViewState on the control.