SQL data not populating in asp webform - asp.net

Currently can not get any SQL data to populate the web form. When I run the report in Visual Studio preview mode, the data populates, however when running through my web app it displays nothing.
Imports System.Data.SqlClient
Public Class topvendors
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
getEntity()
' startdate.Text = DateTime.Today.ToShortDateString
End If
End Sub
Protected Sub getEntity()
Dim strConnString As String = Session("strconnection") 'ConfigurationManager.ConnectionStrings("TrialConnectionString").ConnectionString
Dim con As New SqlConnection(strConnString)
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "pGetProjectsByUser"
cmd.Parameters.Add("#employeeid", SqlDbType.Int).Value = Session("userid")
cmd.Parameters.Add("#reportid", SqlDbType.Int).Value = Request.QueryString("id")
cmd.Connection = con
Try
con.Open()
Dim dt As New DataTable()
Dim ds As New DataSet()
'Dim db As New SqlDataAdapter(cmd)
Dim da = New SqlDataAdapter(cmd)
da.Fill(ds)
'db.Fill(ds)
division.DataSource = ds.Tables(0)
division.DataTextField = "entityname"
division.DataValueField = "entitycode"
division.DataBind()
' If ds.Tables(0).Rows.Count > 1 Then
'divisions.Visible = False
' communities.DataSource = ds.Tables(1)
'communities.DataTextField = "Projectname"
' communities.DataValueField = "projID"
' communities.DataBind()
' Else
' divisions.Text = ds.Tables(0).Rows(0)("entityname").ToString
'division.Visible = False
' communities.DataSource = ds.Tables(1)
'communities.DataTextField = "Projectname"
'communities.DataValueField = "projID"
'communities.DataBind()
'End If
Catch ex As Exception
Throw ex
Finally
con.Close()
con.Dispose()
End Try
End Sub
Protected Sub submit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles submit.Click
' Dim communities As String = Server.UrlEncode(Request.Form("communities"))
' Response.Write(communities)
' Dim removedays As Integer = Request.Form("removedays")
'getEntity()
' MsgBox(sort.SelectedValue)
Dim builder As New System.Data.SqlClient.SqlConnectionStringBuilder
builder = New SqlConnectionStringBuilder(Session("strconnection"))
Dim databasename As String = builder.InitialCatalog
Dim dataname As String
If databasename = "G3Live" Then
dataname = "2fLiveReports"
Else
dataname = "2fTestReports"
End If
Response.Redirect("http://g3reports.danryanbuilders.com/ReportServer/Pages/ReportViewer.aspx?%" + dataname + "%2fPurchasing%2flance_tutorial&rs:Format=Excel&rs%3aCommand=Render&entityid=" & division.SelectedValue & "&begindate=" + begindate.Text + "&enddate=" + enddate.Text + "&sort=" + DropdownList1.SelectedValue)
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim builder As New System.Data.SqlClient.SqlConnectionStringBuilder
builder = New SqlConnectionStringBuilder(Session("strconnection"))
Dim databasename As String = builder.InitialCatalog
Dim dataname As String
If databasename = "G3Live" Then
dataname = "2fLiveReports"
Else
dataname = "2fTestReports"
End If
Response.Redirect("http://g3reports.danryanbuilders.com/ReportServer/Pages/ReportViewer.aspx?%" + dataname + "%2fPurchasing%2flance_tutorial&rs:Format=PDF&rs%3aCommand=Render&entityid=" & division.SelectedValue & "&begindate=" + begindate.Text + "&enddate=" + enddate.Text + "&sort=" + DropdownList1.SelectedValue)
End Sub
End Class

Note: You are storing connection string in Session, it is not recommendable. You can do but it is better you should use web.config
file to store connection string.
You can be refer this: Avoid storing connection string in session for different sql schema
For Solution I recommended
You must check the session variable prior to getting the value for the connection string.
' Check if session is null
If Not (Session("strconnection ") Is Nothing) Then
{
//
}
When it is Null or Nothing or Empty, try to retrieve the connection string again.
You need to cast session variables into their correct types, before use like
Session("strconnection")
Replace it by
Session("strconnection").toString()
And
Cast Session("userid") and Request.QueryString("id") by the help of
Integer.Parse/ Integer.TryParse
you can read this for concept:
Return Value From Session

Related

end of statement expected in vb.net while storing value to the object?

Protected Sub Email_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
Dim objExport As ClsItextSharp = New ClsItextSharp()
Dim strPath As String = ""
Dim objReport As Report = New Report()
objReport = (Telerik.Reporting.Report)RViewer.Report
strPath = CreatePDfwithPath1(objReport)
Dim docType As String = "EncounterNote"
Dim Imgop As ImageOperations = New ImageOperations()
Dim Path As String = Imgop.EncriptString(strpath)
Response.Redirect("../EMail/SendMail.aspx?send=M&Type=nothing&strpath=" + Path + "")
End Sub
end of statement expected in vb.net while storing value to the object? getting error on objReport = (Telerik.Reporting.Report)RViewer.Report.
What is this, C#?
objReport = (Telerik.Reporting.Report)RViewer.Report
I guess you want to cast it:
Dim objReport = CType(RViewer.Report, Telerik.Reporting.Report)

Add new data to textbox when selecting item from combobox

How can I automatically input a number to a textbox after clicking a button upon selecting an item from a combobox. All I know to do is to get the data from the combobox to textbox. But what I would like to do is to add data to a textbox once the item is selected.
This is My Code:
Imports System.Data.OleDb
Imports System.Data
Public Class voting1
Dim con As New OleDbConnection
Dim Com As New OleDbCommand
Dim ComInsert As New OleDbCommand
Dim ComUpdate As New OleDbCommand
Dim ComDelete As New OleDbCommand
Dim aAdapter As New OleDbDataAdapter
Dim Dset As New DataSet
Private Sub voting1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim ConProvider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=J:\EvS\EVS.accdb"
Try
Try
con.ConnectionString = ConProvider
If Not con.State = ConnectionState.Open Then
con.Open()
End If
Catch ex As Exception
MsgBox("No Connection Established")
End Try
Me.fill()
user.Visible = False
user.Text = Form1.usertxt.Text
Catch ex As Exception
End Try
End Sub
Private Sub fill()
With aAdapter
.SelectCommand = New OleDb.OleDbCommand()
.SelectCommand.CommandText = "select * from candidate"
.SelectCommand.Connection = con
End With
Dim dataRead As OleDb.OleDbDataReader
dataRead = aAdapter.SelectCommand.ExecuteReader()
While (dataRead.Read())
presbox.Items.Add(dataRead("President"))
vpbox.Items.Add(dataRead("VicePresident"))
secbox.Items.Add(dataRead("Secretary"))
treasbox.Items.Add(dataRead("Treasurer"))
End While
aAdapter.Dispose()
End Sub
Public Sub Initialize()
Try
If Not con.State = ConnectionState.Open Then
con.Open()
End If
Catch ex As System.Exception
MsgBox(ex.Message, MsgBoxStyle.Information, "ERROR CONNECTION")
End Try
End Sub
Private Sub bo()
Dim con1 As New OleDbConnection
Dim cmd As New OleDbCommand
con1.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=J:\EvS\EVS.accdb"
cmd.Connection = con1
con1.Open()
Dim num As Integer
cmd.CommandText = "SELECT pres1 FROM vote1"
If IsDBNull(cmd.ExecuteScalar) Then
num = 1
samp.Text = num
Else
num = 1
samp.Text = num
End If
cmd.Dispose()
con1.Close()
con1.Dispose()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Call Initialize()
If presbox.Text = "" Or vpbox.Text = "" Or secbox.Text = "" Or treasbox.Text = "" Then
MsgBox("All Fields are required, Check the fields", MsgBoxStyle.Information, "Required Fiels")
Exit Sub
End If
With aAdapter
.SelectCommand = New OleDb.OleDbCommand()
.SelectCommand.CommandText = "select * from [vote] where username = '" & user.Text & "'"
.SelectCommand.Connection = con
End With
Dim dataRead As OleDb.OleDbDataReader
dataRead = aAdapter.SelectCommand.ExecuteReader()
If Not dataRead.HasRows Then
ComInsert.CommandText = "INSERT INTO vote([username],[president],[vicePresident],[secretary],[treasurer])" & _
"VALUES('" & user.Text & "','" & presbox.Text & "','" & vpbox.Text & "','" & secbox.Text & "','" & treasbox.Text & "')"
ComInsert.Connection = con
ComInsert.ExecuteNonQuery()
MsgBox("Voting Successful!", MsgBoxStyle.Information, "NEW RECORD")
Form1.Show()
Me.Close()
aAdapter.Dispose()
ComInsert.Dispose()
Else
MsgBox("WARNING: User Voted Already!!", MsgBoxStyle.Exclamation, "ERROR SAVING DATA")
Me.Close()
Form1.Show()
End If
Catch ex As Exception
End Try
End Sub
End Class
There are a couple of ways to do this if I am understanding what you are wanting.
1.) We can just check if there is anything in the combobox.text property.
If String.IsNullOrEmpty(cbobox.text) Then
Perform the logic of adding data to textbox here.
cbobox.text = null
End If
That is the most simple way, but you will have to set the combobox back to null after the data is added to make it work again.
2.) We can make use of the Combobox.SelectedIndexChanged method.
Here is the documentation website: http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectedindexchanged.aspx
Here is an example:
private void ComboBox1_SelectedIndexChanged(object sender,
System.EventArgs e)
{
perform logic here
}
Hope this helps.
Private Sub p1()
If Not con.State = ConnectionState.Open Then
con.Open()
End If
Com = con.CreateCommand
Com.CommandText = "SELECT COUNT(vote.presnum) as countofpres FROM vote WHERE presnum ='1';"
Dim dt As OleDb.OleDbDataReader = Com.ExecuteReader
dt.Read()
Dim countpres As Integer = dt("countofpres")
Me.pres1.Text = countpres
dt.Close()
End Sub
here it is Jlott

Persisting datatables in viewstate and databinding

I am passing in a start date, an end date, a SQL stored procedure, and a identifying area code into a shared function to populate five declared datatables.
Public Shared Function getNBOCAPData(ByVal startDate As DateTime, ByVal endDate As DateTime, ByVal sp As String, ByVal orgCode As String) As DataTable
Dim SqlConn As New SqlConnection(ConfigurationManager.ConnectionStrings("CancerRegisterConnectionString").ConnectionString.ToString)
Dim sqlCmd As New SqlCommand
getNBOCAPData = New DataTable
Try
SqlConn.Open()
sqlCmd.CommandType = CommandType.StoredProcedure
sqlCmd.Connection = SqlConn
sqlCmd.CommandTimeout = 300
sqlCmd.CommandText = sp
sqlCmd.Parameters.AddWithValue("#StartDate", startDate)
sqlCmd.Parameters.AddWithValue("#EndDate", endDate)
sqlCmd.Parameters.AddWithValue("#UserOrgCode", orgCode)
Dim reader As SqlDataReader = sqlCmd.ExecuteReader()
getNBOCAPData.Load(reader)
Catch ex As Exception
Common.LogError(ex, True)
Finally
SqlConn.Close()
SqlConn.Dispose()
End Try
End Function
The results of this function are then passed into the datatables like this
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim patiDataTable As DataTable = getNBOCAPData(Request.QueryString("startDate"), Request.QueryString("endDate"), "NBOCAP_DOWNLOAD_PATI", Request.QueryString("orgCode"))
Dim tumDataTable As DataTable = getNBOCAPData(Request.QueryString("startDate"), Request.QueryString("endDate"), "NBOCAP_DOWNLOAD_TUM", Request.QueryString("orgCode"))
Dim surDataTable As DataTable = getNBOCAPData(Request.QueryString("startDate"), Request.QueryString("endDate"), "NBOCAP_DOWNLOAD_SUR", Request.QueryString("orgCode"))
Dim cheDataTable As DataTable = getNBOCAPData(Request.QueryString("startDate"), Request.QueryString("endDate"), "NBOCAP_DOWNLOAD_CHE", Request.QueryString("orgCode"))
Dim patDataTable As DataTable = getNBOCAPData(Request.QueryString("startDate"), Request.QueryString("endDate"), "NBOCAP_DOWNLOAD_PATH", Request.QueryString("orgCode"))
Dim hidCount As Integer = 0
If patiDataTable.Rows.Count = 0 Then
divPati.Visible = False
hidCount += 1
End If
If tumDataTable.Rows.Count = 0 Then
divTum.Visible = False
hidCount += 1
End If
If surDataTable.Rows.Count = 0 Then
divSur.Visible = False
hidCount += 1
End If
If cheDataTable.Rows.Count = 0 Then
divChe.Visible = False
hidCount += 1
End If
If pathDataTable.Rows.Count = 0 Then
divPath.Visible = False
hidCount += 1
End If
If hidCount = 5 Then
divNoResults.Visible = True
divInstructions.Visible = False
Else
ViewState("patiDataTable") = patiDataTable
ViewState("tumDataTable") = tumDataTable
ViewState("surDataTable") = surDataTable
ViewState("cheDataTable") = cheDataTable
ViewState("pathDataTable") = pathDataTable
End If
End Sub
The databinding is done like this
Public Shared Sub RetRptBySPNBOCAP(ByRef dg As GridView, ByVal dataTable As DataTable)
dg.DataSource = dataTable
dg.DataBind()
End Sub
Then in preparation for the datatables to be sent to an Excel file the data in ViewState is set to a DataTable like this, but the dataTable.Rows.Count() is throwing a NullReferenceException error as though the databind isn't taking place?
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim cellDate As DateTime = DateTime.MinValue
Dim dataTable As DataTable = Nothing
Dim prefix As String = "Pati_NBOCAP"
Select Case (Request.QueryString("type").ToString)
Case "Pati"
dataTable = ViewState("patiDataTable")
Case "Tum"
dataTable = ViewState("tumDataTable")
prefix = "Tum_NBOCAP"
Case "Che"
dataTable = ViewState("cheDataTable")
prefix = "Che_NBOCAP"
Case "Path"
dataTable = ViewState("pathDataTable")
prefix = "Path_NBOCAP"
Case "Sur"
dataTable = ViewState("surDataTable")
prefix = "Sur_NBOCAP"
End Select
RetRptBySPNBOCAP(Results, dataTable)
Dim rCount As Integer
If dataTable.Rows.Count() > 0 Then
rCount = dataTable.Rows.Count()
End If
End Sub
You must know that viewstate is a per page concept. So if you put data in the viewstate of a particular page you can't retrieve them from another page. Instead of viewstate you can use Session which is the same for all the pages executed within a user session.
Session("patiDataTable") = patiDataTable
Also, viewstate is by default stored client side ans thus is not suitable for large data objects such as datatables.

How to pass only checked values form a list of check boxes in asp.net using vb

Im trying to pass only checked values to a database. But my problem is that even the unchecked values are being passed. My check boxes are created dynamically form a Dropdown box.
Creation of List box form a Drop Down Box
Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
Dim uname As String
Dim sqlConnection As New SqlConnection(connectionString)
sqlConnection.Open()
Dim exe1 As String = "select USERNAME from dummy_tbl_first AS L INNER JOIN Dummy_tbl_second AS A ON L.USER_ID= A.USER_ID INNER JOIN Dummy_tbl3 AS G ON G.GROUP_ID=A.GROUP_ID WHERE G.GROUP_NAME='" + DropDownList1.Text + "' ORDER BY USERNAME "
Dim thisCommand As New SqlCommand(exe1, sqlConnection)
thisCommand.ExecuteNonQuery()
Dim thisReader As SqlDataReader = thisCommand.ExecuteReader()
CheckBoxList1.Items.Clear()
While (thisReader.Read())
uname = thisReader.GetValue(0)
CheckBoxList1.Items.Add(uname)
End While
thisCommand.Dispose()
sqlConnection.Close()
Button1.Enabled = False
End Sub
And this is how i insert into database
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim id As Integer = Request.QueryString("sr_id")
Dim first_name37 As String = CType(Session.Item("FIRST_NAME"), String)
Session("FIRST_NAME") = first_name37
Dim update_id As String = Request.QueryString("sr_id")
For Each list As ListItem In CheckBoxList1.Items
Response.Write(list.Selected)
Dim da As Date = Date.Now()
Dim sqlConnection As New SqlConnection(connectionString)
sqlConnection.Open()
Dim exe1 As String = "INSERT INTO TEST_TBL VALUES('" & id & " ','" + first_name37 + "','" + list.Value + "','" + da + "')"
Dim thisCommand As New SqlCommand(exe1, sqlConnection)
thisCommand.ExecuteNonQuery()
Dim exeupdate As String = "UPDATE TEST_TBL2 SET STATUS='ASSIGNED' WHERE CR_ID='" + update_id + "'"
Dim thisCommandUpdate As New SqlCommand(exeupdate, sqlConnection)
thisCommandUpdate.ExecuteNonQuery()
sqlConnection.Close()
Next
CheckBoxList1.Items.Clear()
Button1.Enabled = False
End Sub
Any help would be much appreciated. Thank you
You need to conditionalise your logic since now it's not discriminating at all. All of the items are in the CheckBoxList1.Items, not just the selected ones; so, check for selected items only...
If (list.Selected) Then
' proceed with this one
End If

How to check a check box automatically on vb.net asp.net?

i have to insert some data value and value like this picture on insert.aspx
And how i show like this to update the data update.aspx
So how to make check box on update.aspx check automatic like on insert.aspx
on Insert.aspx.vb
Protected Sub insertdata()
Dim cls As New connections
cls.openconnections()
Dim cmd As New SqlClient.SqlCommand
cmd.Connection = cls.cn
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "sp_inserttrainer"
cmd.Parameters.AddWithValue("#id", txtKode.Text)
cmd.Parameters.AddWithValue("#nama", txtnama.Text)
cmd.Parameters.AddWithValue("#status", txtstatus.SelectedValue)
cmd.Parameters.AddWithValue("#alamat", txtalamat.Text)
cmd.Parameters.AddWithValue("#telp", txttel.Text)
cmd.Parameters.AddWithValue("#hp", txthp.Text)
cmd.Parameters.AddWithValue("#email", txtemail.Text)
cmd.ExecuteNonQuery()
cls.closeconnection()
End Sub
Protected Sub savedatamateri()
Dim cbterpilih As Boolean = False
Dim cb As CheckBox = Nothing
Dim n As Integer = 0
Do Until n = gridsecond.Rows.Count
cb = gridsecond.Rows.Item(n).FindControl("chkStatus")
If cb IsNot Nothing AndAlso cb.Checked Then
cbterpilih = True
Dim cls As New connections
cls.openconnections()
Dim cmd As New SqlClient.SqlCommand
cmd.Connection = cls.cn
cmd.CommandText = "Insert Into m_trainer_detil (trainer_id, materi_id)"
cmd.CommandText &= "values(#triner, #materi)"
Dim com As HiddenField = CType(gridsecond.Rows(n).FindControl("HiddenField2"), HiddenField)
cmd.Parameters.AddWithValue("#triner", txtKode.Text)
cmd.Parameters.AddWithValue("#materi", com.Value)
cmd.ExecuteNonQuery()
cls.closeconnection()
End If
n += 1
Loop
End Sub
Protected Sub insert_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles insert.Click
If txtalamat.Text = "" Then
labelran.Text = "Tolong isi Alamat"
ElseIf txtemail.Text = "" Then
labelran.Text = "Tolong isi Email"
ElseIf txtnama.Text = "" Then
labelran.Text = "Tolong isi Nama"
ElseIf txttel.Text = "" Then
labelran.Text = "Tolong isi Telepon"
ElseIf txthp.Text = "" Then
labelran.Text = "Tolong isi Handphone"
Else
insertdata()
savedatamateri()
listhendle()
End If
End Sub
and for update.aspx.vb
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
listhendle()
listmateri()
End If
End Sub
Protected Sub listhendle()
Dim ds As New DataSet
Dim cls As New connections
ds = cls.returndataset("select * from [m_trainer] ")
If ds.Tables(0).Rows.Count = 0 Then
ds.Tables(0).Rows.Add(ds.Tables(0).NewRow)
End If
griddata.DataSource = ds
griddata.DataBind()
End Sub
Protected Sub listmateri()
Dim ds As New DataSet
Dim cls As New connections
ds = cls.returndataset("select * from [m_materi] ")
If ds.Tables(0).Rows.Count = 0 Then
ds.Tables(0).Rows.Add(ds.Tables(0).NewRow)
End If
gridsecond.DataSource = ds
gridsecond.DataBind()
End Sub
Protected Sub griddata_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles griddata.SelectedIndexChanging
Dim kode As HiddenField = CType(griddata.Rows(e.NewSelectedIndex).FindControl("HiddenField1"), HiddenField)
txtKode.Text = kode.Value
txtnama.Text = Replace(griddata.Rows(e.NewSelectedIndex).Cells(1).Text, " ", "")
txtalamat.Text = Replace(griddata.Rows(e.NewSelectedIndex).Cells(2).Text, " ", "")
txttel.Text = Replace(griddata.Rows(e.NewSelectedIndex).Cells(3).Text, " ", "")
txthp.Text = Replace(griddata.Rows(e.NewSelectedIndex).Cells(4).Text, " ", "")
txtstatus.SelectedValue = Replace(griddata.Rows(e.NewSelectedIndex).Cells(5).Text, " ", "")
txtemail.Text = Replace(griddata.Rows(e.NewSelectedIndex).Cells(6).Text, " ", "")
End Sub
But i don't know how connect materi with database
Thank You
It looks like you are storing the materi_id in the table m_trainer. So it looks like you would need to set up an OnRowDataBound event on your "gridSecond" GridView. Within the OnRowDatabound event get a dataset for the selected trainer_id and if the materi_id exists within that dataset set its checked value as true.

Resources