How can I have 2 gridviews in one form with same dataset, but other population? - vb.net

Here you see my code of a form with 2 gridviews. Both have the same dataset, bindingsource. The dataset which is made out of a datasource, has 2 different sql queries.
filld() and fillauswahl() filld shows in the gridview a "select distinct" query.
When the user hits the button1, the selected item from that gridview is saved in "verzeichnis1" this var gets pasted to fillauswahl() which is
select* from mytable where columnx = verzeichnis1
The problem I have is that both gridviews get filled during formload with filld() and by clicking the button with fillverzeichnis() i dont know how to seperate that!? i guess it´s very easy. Cheers and thanks
Public Class Importverzeichnis
Public verzeichnis1 As String
Private Sub Importverzeichnis_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Me.SKM2TableAdapter.Filld(Me.SLXADRIUMDEVDataSet.SKM2)
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each cell As DataGridViewCell In DataGridView1.SelectedCells
verzeichnis1 = cell.Value
Next
Me.SKM2TableAdapter.Fillauswahl(Me.SLXADRIUMDEVDataSet.SKM2, verzeichnis1)
End Sub
End Class
Edit: I created a new connection a new datset and new dataadapter and now it works:
Dim connectionString As String = My.Settings.SLXADRIUMDEVConnectionString
Dim sql As String = "SELECT * FROM SKM2 where
Benutzerdefiniert_10 ='" & verzeichnis1 & "' "
Dim connection As New SqlConnection(connectionString)
Dim dataadapter As New SqlDataAdapter(sql, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "verzeichnis")
connection.Close()
datagridview2.DataSource = ds
datagridview2.DataMember = "verzeichnis"
but I would be more happy if can use my first dataset and my first adapter. If anyobdy knows how I can do this, I would be happy for the answer

To me the best way would be to just pull down the data as a your normal select statement and then filter the data in your code-behind. By populating a dataset with the same data twice your just making the traffic from the database slower. However, if you wish to keep your current dataset, I would assume that there are two tables in it, one for each select. If that is the case then change:
datagridview2.DataSource = ds
to:
datagridview2.DataSource = ds.Tables(1) 'assumes the second table is used for this datasource

Related

VB.Net Combo Box Number from Query

So i have a database with 2 rows code,name lets say its like
code / name
1 / john
2 / george
i use this query to bring them in my combo box .
strConnection = String.Format("Provider=SQLOLEDB;Data Source={0};Initial Catalog={1};User ID={2};Password={3};",
strServer, strDataBase, strUserName, strPassword)
Dim Connection As New OleDbConnection(strConnection)
Connection.Open()
Dim cm As New OleDbCommand("SELECT Codeid [Κωδικός],descr [Περιγραφή] FROM EMBONILO_B.DBO.manufacturer GROUP BY Codeid,descr", Connection)
Dim dr As OleDbDataReader = cm.ExecuteReader
While dr.Read
ComboBox.Items.Add(dr(1).ToString)
End While
dr.Close()
Connection.Close()
and it show the name john and george. What i want is when you click the combo box and you select a name i want the code to appear on the combo box lets say if its george selected i want number 2 in combo box etc.
Thanks for advance.
When you are adding items to the ComboBox you are only setting the Text property, not the Value property. ComboBox.Items.Add() should have an overload where you can do specify the Value as well when you had items in your While loop, something like ComboBox.Items.Add(dr(1).ToString(), dr(0).ToString()) or maybe ComboBox.Items.Add(New ListItem(dr(1).ToString(), dr(0).ToString())) if you are using ASP.NET WebForms for example. Either way, each list item will have separate Text and Value properties; you want to put the ID in the Value property, and you can subsequently get the selected ID in your code using ComboBox.SelectedValue or similar, depending upon the control you are using for a combobox.
My assumption is you really want to obtain the ID in code to store in a db table, not display it in the UI.
This all applies to a WinForms application.
Declare a Form level variable to hold the CodeID of the currently selected descr in the combobox.
Since GetDescriptionData is called from Form.Load the values strServer, strDatabase etc. used in the connection string, must be available at this time. If they are not available until some user input is gathered move the code to a button. .DisplayMember and .ValueMember are names of fields from the Select statement.
Separate the data access code from the user interface code. Connections and commands need to be closed and disposed. Using...End Using blocks take care of that for us.
The form level variable CurrentCodeID is set in the ComboBox.SelectedIndexChanged event.
Private CurrentCodeID As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ComboDataTable = GetDescriptionData()
ComboBox1.DisplayMember = "descr"
ComboBox1.ValueMember = "Codeid"
ComboBox1.DataSource = dt
End Sub
Private Function GetDescriptionData() As DataTable
Dim dt As New DataTable
Dim strConnection = String.Format("Provider=SQLOLEDB;Data Source={0};Initial Catalog={1};User ID={2};Password={3};",
strServer, strDataBase, strUserName, strPassword)
Using Connection As New OleDbConnection(strConnection),
cm As New OleDbCommand("SELECT Codeid,descr FROM EMBONILO_B.DBO.manufacturer;", Connection)
Connection.Open()
dt.Load(cm.ExecuteReader)
End Using
Return dt
End Function
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
CurrentCodeID = ComboBox1.SelectedValue.ToString
End Sub

Add column to SQL table and populate to datagridview

I have a windows form application with databound datagridview. I want to add column at run time (if user wants to add more column to it). So on button click I wanted to add column. I have added following code to event it adds column in server explorer view under tables column's list but does not show in table definition neither in data source window (in column list under table) nor in datagridview.
Imports System.Configuration
Imports System.Data.SqlClient
Public Class Form3
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Small_databaseDataSet.newtable' table. You can move, or remove it, as needed.
Me.NewtableTableAdapter.Fill(Me.Small_databaseDataSet.newtable)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AddColumn()
End Sub
Private Sub AddColumn()
Dim connString As String = "Data Source=(localDb)\ProjectsV13;Initial Catalog=small database;Integrated Security=True"
Dim dt As New DataTable
Using conn As New SqlConnection(connString)
Dim str As String = "ALTER TABLE newtable ADD " & TextBoxX1.Text & " INT null;"
Using comm As New SqlCommand(str, conn)
conn.Open()
comm.ExecuteNonQuery()
End Using
End Using
Validate()
DataGridViewX1.Columns.Clear()
NewtableTableAdapter.Update(Small_databaseDataSet.newtable)
NewtableTableAdapter.Fill(Small_databaseDataSet.newtable)
DataGridViewX1.DataSource = NewtableBindingSource
End Sub
End Class
Change this line of code:
' Add the keyword NULL and brackets around the column name
Dim comm As New SqlCommand("ALTER TABLE testTable ADD [col1] INT NULL", conn)
If I wanted to have the new column to show up automatically, I would re-query the database, retrieving the data on that table and just set the datagridview datasource to the resultset like:
'I assume the datagridview name is DataGridView1
DataGridView1.Columns.Clear()
DataGridView1.DataSource = USTDatabaseDataSet
DataGridView1.DataMember = "testTable"
DataGridView1.DataBind()
A DataReader is used to retrieve data. Since there is no data retrieved nothing is loaded into your DataTable except maybe a return value of success or failure. The Using statements ensure that your objects are closed and disposed properly even if there is an error.
Private Sub AddColumn()
Dim connString As String = ConfigurationManager.ConnectionStrings("USTDatabaseConnectionString").ConnectionString
Dim dt As New DataTable
Using conn As New SqlConnection(connString)
Using comm As New SqlCommand("ALTER TABLE testTable ADD col1 INT;", conn)
conn.Open()
comm.ExecuteNonQuery()
End Using
Using com2 As New SqlCommand("Select * From testTable;", conn)
Using reader As SqlDataReader = com2.ExecuteReader
dt.Load(reader)
conn.Close()
End Using
End Using
End Using
DataGridView1.DataSource = dt
End Sub

how to pass multiple values using single textbox in vb.net?

I am doing vb.net programming. In that, I am using one textbox, one gridview and one button. Now, I want to pass queries into the textbox and when clicking on button, I want to display the result into the datagridview.
i.e suppose i am passing selection query and clicking on button at that time i want to display the table data into the datagridview.
I don't know what Db you are using but I have an example using Sql.
Example:
You want to get the Name from the Students Db.
Dim dt As New DataTabale
Dim con As New SqlConnection("connection")
Dim cmd As New OdbcCommand("SELECT * FROM [Students] WHERE [Name] = #Name", con)
con.Open()
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = TextBox.Text
dt.Load(cmd.ExecuteReader())
GridView1.DataSource = dt
GridView.DataBind()
You can place this code on Button.
Ps. I view your the edit history of your code and I saw that you are using Db.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim query As String = TextBox1.Text
Try
SqlDataSource1.SelectCommand = query
SqlDataSource1.DataBind()
Catch ex As Exception
MsgBox("No results returned")
End Try
End Sub

Changes in Datagridview not saving in table SQLite vb.net

I'm trying to save changes made to datagridview into the table tbl_invent, the changes i make commits to datagridview but it does not save to the table (database), also it doesn't have any error, all i received is a message saying "Records Updated = 0". anyone could point me to the right direction?
Dim da As New SQLiteDataAdapter("select * from tbl_Invent", connection)
Dim ds As New DataSet
'Dim cmdbuilder As New SQLite.SQLiteCommandBuilder(da)
Dim i As Integer
da.TableMappings.Add("tbl_Invent", "tbl_Invent") 'add due to error unable to Update unable to find TableMapping['Table'] or DataTable 'Table'
Try
i = da.Update(ds, "tbl_Invent")
MsgBox("Records Updated= " & i)
Catch ex As Exception
MsgBox(ex.Message)
End Try
connection.Close()
i already check out this thread:
How to save changes from DataGridView to the database?
-and-
Datagridview save changes to Database vb.net
thank you very much in advance.
It should be obvious that you're not going to save any changes if you don't make any changes between creating/populating your DataTable and trying to save the changes. You need to create the DataTable, populate it and bind it in one method (probably the Load event handler of the form), then the user makes the changes, then you save the changes from the same DataTable in another method (probably the Click event handler of a Button. E.g.
Private table As New DataTable
Private adapter As New SqlDataAdapter("SQL query here", "connection string here")
Private builder As New SqlCommandBuilder(adapter)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
adapter.Fill(table)
BindingSource1.DataSource = table
DataGridView1.DataSource = BindingSource1
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BindingSource1.EndEdit()
adapter.Update(table)
End Sub
The DataTable is created when the form is, the user makes the changes in the grid and clicks the Button and then you save the changes from THE SAME DataTable, not a new one that you just created that contains no changes.

how to update, insert records through datagridview to sql using data adapter or other method in vb.net

hello best programmers in the world i need your expert advise and assistance with regards to my project.
I am trying to insert and update my table through datagridview by clicking a command button,
i have my datagridview properties set to editmode : editprogrammatically,
here's the code, of where i pulled up my datagridview content:
Public Sub loaddgvfrm3()
cmdconn = New SqlConnection
cmd = New SqlCommand
cmdconn.ConnectionString = sqlstr
cmdconn.Open()
cmd.Connection = cmdconn
cmd.CommandText = "select period, VOUCH_AMT, INDIVIDUAL_AMT, check_no, D_MAILED, DIR_NO from tobee.EBD_BILLHISTORY where CLAIM_NO like '" + txtClaimno.Text + "'"
Dim dt As New DataTable
da = New SqlDataAdapter
da.SelectCommand = cmd
da.Fill(dt)
Me.DataGridView1.DataSource = dt
Me.DataGridView2.DataSource = dt
cmdconn.Close()
End Sub
now i have my command buttons here
here's the add button: (im prefering to add a row within the selected table)
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
End Sub
here's the Edit button:
Private Sub btnEditmain_Click(sender As Object, e As EventArgs) Handles btnEditmain.Click
''Form1.ShowDialog()
'DataGridView2.AllowUserToAddRows = True
''DataGridView2.BeginEdit(True)
'btnSave.Enabled = True
End Sub
and here's the save button that should save all changes that i have done,
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim connstr As String = "server=midtelephone\sqlexpress; database=testdb; user= sa; password=sa;"
End Sub
i left command button contents empty because i need to create a new method of inserting, updating the row. because the one that i have earlier was a fail, although it inserts the data in the sql, but not in its appropriate row, take a look at here: Data inserted from datagridview not updated in SQL Server , instead it creates another row which is not connected with '" + txtClaimno.Text + "'" (stated from above) so what happens is that it stacks a new row with no connected owner from another table(claim_no < this claim_no is connected from another table as a fk in the database but a primary key in (billhistory table))
can you pls help me get rid of this problem as i am having a hard time moving to the next phase of our project? im just a high school student, so pls bear with me :) i'll appreciate if u give comments / answers regarding my question :) thanks in adv.
my mentor advised me to use data adapter accept changes stuff, but i don't know how to implement such stuffs. pls help me thank you :)
Use Event to get data from gridview on cellConttent Click and these values to a query or Stored procedure.
private void grdCampaignStats_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
//I want to get value of SomeColumn of grid view having datatype String
string SomeVariabel = grd["CoulmnNameinGRID", e.RowIndex].Value.ToString();
// Make it according to Vb it is C# code
}