loop through datatable and run stored procedure - asp.net

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)

Related

How to Use forloop inside the list of sqlparameter?

How to add my data gridview value into database i m using dal my code is this
Dim list As New List(Of SqlParameter)
For each row as DataGridView In DataGridView1.Rows
If row.cell(0).value isnot nothing
Qry="insert into sale1(Description)values(#1)"
With list
.add(new Sqlparameter("#1",row.cells(2).value)
End with
End if
Next
If you don't want to do as #jmcilhinney suggested in comments (the best way), this should work as closest to the code you provided but it does not separate database code form user interface code.
The idea is to add the parameter once outside the loop and then just change the value in the loop. I had to guess at the datatype and size of the parameter. Please check your database and correct the code.
Private Sub OPCode2()
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand("insert into sale1 (Description)values(#1)", cn)
cmd.Parameters.Add("#1", SqlDbType.NVarChar, 300)
cn.Open()
For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells(0).Value IsNot Nothing Then
cmd.Parameters("#1").Value = row.Cells(2).Value
cmd.ExecuteNonQuery()
End If
Next
End Using
End Sub
To separate the code...
Private Sub UICode()
Dim lst As New List(Of String)
For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells(0).Value IsNot Nothing Then
lst.Add(row.Cells(2).Value.ToString)
End If
Next
UpdateDatabase(lst)
End Sub
Private Sub UpdateDatabase(lst As List(Of String))
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand("insert into sale1 (Description)values(#1)", cn)
cmd.Parameters.Add("#1", SqlDbType.NVarChar, 300)
cn.Open()
For Each s As String In lst
cmd.Parameters("#1").Value = s
cmd.ExecuteNonQuery()
Next
End Using
End Sub

Data inserted in two different rows

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

Web form - sql and retrieving data - is there simpler solution

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.

GridView + Access Database

I'm trying to link Access database with GridView control.
Here's the question:
One successful procedure to link database query.
Protected sub Query(ByVal y as string)
Dim da As New OleDbDataAdapter(y, cn)
Dim dt As New DataTable()
da.Fill(dt)
da.Dispose()
cn.Dispose()
Me.GridView1.DataSource = dt
Me.GridView1.DataBind()
ListBox1.Visible = True
End sub
What I wanted is to re-run query if the first run returns no value/result in another procedure.
Protected Sub btnFind_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFind.Click
x = "SELECT * From Class Where Gender ='Male' And First_name ='James' "
Query(x)
If gridview.rows.count =0 then
x= "SELECT * From Class Where Gender ='Male'"
query(x)
End If
then put result into listbox.
However, I got error of "The ConnectionString property has not been initialized." on da.Fill(dt) when running the second time. First time was successful.
OK I finally got mistake corrected. I gotta Dim cn As New OleDbConnection("Provider = Microsoft.JET.OLEDB.4.0;" & "Data Source = C:\Class.mdb") again to use query instead of once for all queries.
Create and dispose the connection in the same method
Protected Sub Query(ByVal y as string)
Dim dt As New DataTable()
Using cn as New OleDbConnection("your_connection_string"), _
da As New OleDbDataAdapter(y, cn)
da.Fill(dt)
End Using
Me.GridView1.DataSource = dt
Me.GridView1.DataBind()
End Sub

How to get work ASP.NET DataSet when connection losts?

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.

Resources