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
Related
I would like to search data in a textbox . Below is my code. I tried to search but nothing happen.
If Not Me.IsPostBack Then
Me.SearchPanelId()
End If
End Sub
Private Sub SearchPanelId()
Dim ConnectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Using con As New SqlConnection(ConnectionString)
Using cmd As New SqlCommand()
Dim sql As String = "SELECT panelid, panelname, paneltype FROM PANEL_TABLE"
If Not String.IsNullOrEmpty(TextBox1.Text.Trim()) Then
sql += " WHERE panelid LIKE #panelid + '%'"
cmd.Parameters.AddWithValue("#panelid", TextBox1.Text.Trim())
End If
cmd.CommandText = sql
cmd.Connection = con
Using sda As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Using
End Sub
Protected Sub Search(sender As Object, e As EventArgs)
Me.SearchPanelId()
End Sub
Protected Sub OnPaging(sender As Object, e As GridViewPageEventArgs)
GridView1.PageIndex = e.NewPageIndex
Me.SearchPanelId()
End Sub
Do the validation before you start creating objects. You need to check if that datatype of the ID is valid. I guessed that this was an Integer type but check your database. If I am wrong and the datatype is .VarChar then see the second rendition. :-) The Like keyword does not make any sense with a numeric field.
Don't use .AddWithValue See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
A DataAdapter is not necessary. Just use the load method of the DataTable.
Private Sub SearchPanelId()
Dim IDValue As Integer
Dim dt As New DataTable
If String.IsNullOrEmpty(TextBox1.Text.Trim()) OrElse Not Integer.TryParse(TextBox1.Text.Trim, IDValue) Then
Return
End If
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
Using cmd As New SqlCommand("SELECT panelid, panelname, paneltype FROM PANEL_TABLE WHERE panelid = #panelid", con)
cmd.Parameters.Add("#panelid", SqlDbType.Int).Value = IDValue
con.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
If Id is a .VarChar
Private Sub SearchPanelId()
Dim dt As New DataTable
If String.IsNullOrEmpty(TextBox1.Text.Trim()) Then
Return
End If
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
Using cmd As New SqlCommand("SELECT panelid, panelname, paneltype FROM PANEL_TABLE WHERE panelid Like #panelid", con)
cmd.Parameters.Add("#panelid", SqlDbType.VarChar).Value = TextBox1.Text.Trim() & "%"
con.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
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'm having a problem when I'm reading data from a SQL Server database. The main thing is that I want to read the data from the database and display the data in a Label control. But the concern is that it can't read data to it. I will show you the code snippet and any comments/suggestions are gladly considered.
Option Explicit On
Imports System.Data
Imports System.Data.OleDb
Partial Class ViewDetail
Inherits System.Web.UI.Page
Dim con As OleDbConnection
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Dim InstructorID As Integer
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
InstructorID = Request.QueryString("Instructor_ID")
Integer.TryParse(lblID.Text, InstructorID)
con = New OleDbConnection("Provider=SQLNCLI11;Data Source=ARIES-PC\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=SchoolDB")
con.Open()
cmd = New OleDbCommand("SelectData", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#id", InstructorID)
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read
lblID.Text = dr("Instructor_ID").ToString
lblFirstname.Text = dr("FirstName").ToString
lblLastname.Text = dr("LastName").ToString
lblAddress.Text = dr("Address").ToString
lblContact.Text = dr("Contact_Number").ToString
End While
End If
dr.Close()
cmd.Dispose()
con.Close()
End Sub
End Class
This line seems to be totally wrong
Integer.TryParse(lblID.Text, InstructorID)
This lines takes the current value in the lblID.Text at the Page_Load event and tries to set the value of InstructorID. But your code seems to want this value from the QueryString passed that contains the real value.
If you are certain the the QueryString contains a valid integer then remove that line and add
InstructorID = Convert.ToInt32(Request.QueryString("Instructor_ID"))
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
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)