Sorry if this question is stupid but I have no other way to see the big picture.
I have 1 textbox, 1 label and database with two columns (codename and description), by entering codename in textbox I would like to get corresponding description in label.
With Excel and VBA it can be done with couple of lines. Sadly I can not use Excel but have to choose Web interface 'cause of slow PCs and Office price. Why is this simple task so complicated in ASP.NET with all general declarations and sqlservers and sqlconnections.
Is there a simpler way to do this?
BTW. I've tried to adapt many different things I've found on the web and this last one looks promising but it doesn't work :
Protected Sub TextBox2_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
Using sqlconn As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=KLIJENTI;Integrated Security=True"), _
sqlcmd As New SqlCommand("Select From Baza Where SIFRE = #SIFRE", sqlconn)
sqlcmd.Parameters.Add("#SIFRE", SqlDbType.VarChar, 50).Value = TextBox2.Text
sqlconn.Open()
'Label1.Text = CString(sqlcmd.ExecuteScalar()) 'CString is not declared
Label1.Text = sqlcmd.ExecuteScalar()
End Using
End Sub
Where Baza is Table name,
SIFRE is codename that will be entered in textbox
and NAZIV is description corresponding to SIFRE and should be shown in Label
The correct form is
Protected Sub TextBox2_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
Using sqlconn = New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=KLIJENTI;Integrated Security=True")
Using sqlcmd = New SqlCommand("Select NAZIV From Baza Where SIFRE = #SIFRE", sqlconn)
sqlcmd.Parameters.AddWithValue("#SIFRE", TextBox2.Text)
sqlconn.Open()
Dim result = sqlcmd.ExecuteScalar()
if result IsNot Nothing Then
Label1.Text = result.ToString
End If
End Using
End Using
End Sub
The SELECT sql clause is followed by the list of columns you want to retrieve. (Added NAZIV)
Also you should consider that your query could not find a value for the parameter #Sifre and, in that case, the result of the ExecuteScalar is Nothing.
Related
I am having a library system database. I want to include a search box where I can search for a book name. I am using sql server. I know how to write a sql statement using the LIKE %''% clause, but the thing is I am writing this sql statement in a separate file and include that in the sub method in vb.net. How can I make that statement use the text entered in textbox?
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim str As String = ("Data Source=.\INSTANCE;initial catalog=example;user=sa;password=gariahat")
Dim con As New SqlConnection(str)
Dim cmd As New SqlCommand("select * from item where book_id like '%" + Trim(TextBox1.Text) + "%'", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
If (da.Fill(ds, "item")) Then
ItemDataGridView.DataSource = ds.Tables(0)
MessageBox.Show("match found")
Else
MessageBox.Show("match not found")
End If
End Sub
I know this sub will work if I include the sql statement in the sub itself. But I use squaler to store my sql stored procedures and use those file in my sub, that file does not accept 'textbox.text'.
Example:
Public Shared Sub AccountDeposit(ByVal value As Integer, ByVal AccountNumber As String, ByVal connection As SqlConnection)
Dim cmd As New SqlCommand("AccountDeposit", connection)
cmd.CommandType = Data.CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#AccountNumber", AccountNumber)
cmd.Parameters.AddWithValue("#Value", value)
cmd.ExecuteNonQuery()
End Sub
Here "AccountDeposit" is my stored procedure which i included in my sub.I want to do similar thing here but dont know how to include the text in textbox to sql statement
I'm trying to insert a raw data and a time stamp into the database. both the data and timestamp have to be in one row. However, when saved, they seem to be inserted into two different cells, two different rows as in the picture.
The code is written in visual basic along with asp.net.
Dim cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= "& Server.MapPath("dbase/DB.mdb"))
Protected Sub btnUSsave_Click(sender As Object, e As EventArgs) Handles btnUSsave.Click
Dim cmd As New OleDbCommand("insert into Quest(US1)values(#a1)", cn)
cmd.Parameters.AddWithValue("a1", TextBox1.Text)
Dim time1 As New OleDbCommand("INSERT INTO Quest(TimeUS1) VALUES (Time())", cn)
cn.Open()
cmd.ExecuteNonQuery()
time1.ExecuteNonQuery()
cn.Close()
Response.Redirect("CountryA2Desc.aspx")
End Sub
Any idea on how to make the data in one row ?
As commented, you just need to use one insert statement instead of two. This should work for you
Protected Sub btnUSsave_Click(sender As Object, e As EventArgs) Handles btnUSsave.Click
Dim cmd As New OleDbCommand("insert into Quest(US1,TIMEUS1) values(#a1,Time())", cn)
cmd.Parameters.AddWithValue("a1", TextBox1.Text)
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
Response.Redirect("CountryA2Desc.aspx")
End Sub
I am currently doing a project on web service for wine. I have the wine table with wineName and wineType. Also I have the search function implemented in the webservice coding as well as a separate webform to call the function of the search function
I have the following code for performing search in the search service:
<WebMethod()> _
Public Function Search(ByVal searchName As String) As System.Data.DataSet
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim con As New SqlConnection(connectionString)
Dim selectSql As String = "SELECT * From Wine WHERE WineType='" & searchName + "'"
Dim selectAdapter As New Data.SqlClient.SqlDataAdapter(selectSql, con)
Dim ds As New Data.DataSet
con.Open()
selectAdapter.Fill(ds, "Wine")
con.Close()
Return ds
End Function
As for the webform, it's just a simple page with textbox labeled as searchName, a button and a gridView1 tied to ObjectDataSource.
This is the coding i have for webform:
Partial Class Search
Inherits System.Web.UI.Page
Dim searching As searchwine.Service = New searchwine.Service
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If searchName.Text = "" Then
lblDisplayError.Text = "Can't search empty field!"
Else
Dim ds As DataSet = searching.Search(searchName.Text)
GridView1.DataSource = ds.Tables(0)
GridView1.DataBind()
GridView1.Visible = True
lblDisplayError.Visible = False
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
lblDisplayError.Text = ""
GridView1.Visible = False
End Sub
End Class
Everything seems fine, but i have the following error when i want to do a search:
System.NullReferenceException: Object reference not set to an instance of an object. at Service.Search(String searchName)
Can anyone help me out please?
I've looked through your code a couple times and I can't see what's causing the NullReferenceException. My best guess is that it couldn't find a connection string name "ConnectionString" in your web.config file, but even that doesn't quite seem to fit.
I can suggest some improvements to your search code. Hopefully you'll at least get a better error message out of this:
<WebMethod()> _
Public Function Search(ByVal searchName As String) As System.Data.DataSet
Dim ds As New Data.DataSet()
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Using con As New SqlConnection(connectionString), _
cmd As New SqlCommand("SELECT * From Wine WHERE WineType= #SearchName", con)
'I had to guess at the exact length and type of the field here
cmd.Parameters.Add("#SearchName", SqlDbType.VarChar, 50).Value = searchName
Dim selectAdapter As New Data.SqlClient.SqlDataAdapter(cmd, con)
selectAdapter.Fill(ds, "Wine")
End Using
Return ds
End Function
But in the end I expect you'll need to step through the method and see exactly which line above throws the exception.
Looks like you are missing a New
Dim ds As DataSet = searching.Search(searchName.Text)
Should be...
Dim ds As **New** DataSet = searching.Search(searchName.Text)
I am trying to loop through a datatable, that will pass information to my stored procedure but it isn't working.
even though it works when i manuelly
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim dv As New DataView
Dim dt As New DataTable
dv = SqlDataSource1.Select(DataSourceSelectArguments.Empty)
dt = dv.ToTable()
For Each row As DataRow In dt.Rows
If row("vtr_gen10").ToString() = "y" Or row("vn10").ToString() = "a" Or row("vtr_gen10").ToString() = "p" Then
Dim SQLCon As New SqlClient.SqlConnection
Dim sqlcmd As New SqlCommand
SQLCon.ConnectionString = SqlDataSource2.ConnectionString
SQLCon.Open()
sqlcmd.CommandText = "protest" ' Stored Procedure to Call
sqlcmd.CommandType = CommandType.StoredProcedure 'Setup Command Type
sqlcmd.Connection = SQLCon 'Active Connection
sqlcmd.Parameters.AddWithValue("#ID", row("id"))
sqlcmd.Parameters.AddWithValue("#Value", "Y")
sqlcmd.ExecuteNonQuery()
SQLCon.Close()
End If
Next
End Sub
Are you absolutely sure the IF criteria is being met after the first two records? One thing to look for is spaces or other string anomalies such as carraige returns in your database...
Row("vn10").ToString for example may for some reason be "a " instead of "a". Might be worth putting in a temporary debug line such as :
Throw New Exception("[" & Row("vn10").ToString & "]")
or inspect length on some records that erroneously fail.
There is nothing seems to be wrong with your code, but if you think its because its moving too fast, try adding sleep using System.Threading.Thread.Sleep(milliseconds)
I made a basic program that connects and gets content from a table via SQL, it's working normally. What I want is; when connection losts via SQL Server or internet connection, it must continue to list items that it got before connection losts instead of giving "Connection Problem Error".
Code is like this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strSQL As String
Dim conn As New SqlConnection
conn.ConnectionString = baglan()
conn.Open()
strSQL = "SELECT * FROM Telefon_Otomasyon"
Dim da As New SqlDataAdapter(strSQL, conn)
Dim dset As New DataSet()
da.Fill(dset, "Telefon_Otomasyon")
Dim Hepsi As DataRow
For Each Hepsi In dset.Tables("Telefon_Otomasyon").Rows
Response.Write(Hepsi("Arayan") & "<br />")
Next
End Sub
Thanks!
What you can do is store your dataset in Session: (excuse my VB, i'm very rusty with it)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strSQL As String
Dim conn As New SqlConnection
conn.ConnectionString = baglan()
conn.Open()
strSQL = "SELECT * FROM Telefon_Otomasyon"
Dim da As New SqlDataAdapter(strSQL, conn)
Dim dset As New DataSet()
Try
da.Fill(dset, "Telefon_Otomasyon")
MyDataset = dset
Catch ex As SqlException
dset = MyDataset
End Try
Dim Hepsi As DataRow
For Each Hepsi In dset.Tables("Telefon_Otomasyon").Rows
Response.Write(Hepsi("Arayan") & "<br />")
Next
End Sub
Private Property MyDataset() As DataSet
Get
return Session("myDataset")
End Get
Set(ByVal value as DataSet)
Session("myDataset") = value
End Set
End Property
This is also a very basic example, it needs to be tidied up before you can use it in production code, i.e. you need to consider what to do if there is no dataset stored in Session (if it returns null). You may want to be a bit smarter than that and just store a specific table. Note that Session can expire though, so do some reading on it. This should be enough to steer you in the right direction.
Further note: if you want something a little less volatile than Session then you could try using the Cache instead.
I'm not sure I understand the problem here. While I'm not a VB-programmer it seems to me like once the page loads it will run the SQL query and then process that dataset.
If you reload the page and the SQL connection isn't working you will get an error that you'd need to handle somehow (not sure how VB exceptions work but I'm sure you can figure that out).
If you on the other hand mean that you want to get whatever data you can from a query that gets disconnected mid-query - I'd say that is pretty hard and only relevant for huge queries.