datagridview combobox - vb.net

I have a datagridview containing 1st column (combobox), 2nd and 3rd column is textbox. The combobox was filled-up using datatable. My problem is on loading form, I will get a records from my database and set the value of my combobox base on those records. So if I have 5 records from my database then I should have 5 rows containing combobox in my datagridview.
Any suggestion would greatly appreciated
I tried the code below but there's an error saying "the following exception occured in the datagridview...." but it will display correctly, but if I click in any cell that error always appear.
Private Sub frmEditIngredientManagement_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
sSQL = "SELECT * FROM fs_nutrient"
ReadSQL(sSQL)
Dim dtNutrient As New DataTable
dtNutrient.Load(reader)
dgvCbxIngredientList.DataSource = dtNutrient
dgvCbxIngredientList.DisplayMember = "ndb_no"
dgvCbxIngredientList.ValueMember = "nutrient_id"
sSQL = "SELECT * FROM fs_ingredient_management_nutrient INNER JOIN fs_nutrient ON fs_ingredient_management_nutrient.nutrient_id = fs_nutrient.nutrient_id WHERE ingredient_management_id = " & intIngredientManagementId & " "
ReadSQL(sSQL)
If reader.HasRows Then
While reader.Read
Dim row As String() = New String() {reader("ndb_no"), "dd", "vv"}
dgvNutrient.Rows.Add(row)
End While
End If
End Sub

Completely new answer. Found a way around the error:
Answer was found in MSDN datagridviewcomboboxcolumn helpfile
Add this routine to "report errors" and forget about the error you get:
Private Sub dgvNutrient_DataError(ByVal sender As Object, ByVal e As DataGridViewDataErrorEventArgs) Handles dgvNutrient.DataError
'MessageBox.Show("Error happened " & e.Context.ToString())
End Sub

Related

VB.NET DataSet table data empty

I'm trying to use the dataset for a report, but the data is gone when I try to use it. Here is my code for the most part:
Variables:
Dim ResultsDataView As DataView
Dim ResultsDataSet As New DataSet
Dim ResultsTable As New DataTable
Dim SQLQuery As String
Search:
This is where a datagrid is populated in the main view. The data shows up perfectly.
Private Sub Search(Optional ByVal Bind As Boolean = True, Optional ByVal SearchType As String = "", Optional ByVal SearchButton As String = "")
Dim SQLQuery As String
Dim ResultsDataSet
Dim LabelText As String
Dim MultiBudgetCenter As Integer = 0
SQLQuery = "A long and detailed SQL query that grabs N rows with 7 columns"
ResultsDataSet = RunQuery(SQLQuery)
ResultsTable = ResultsDataSet.Tables(0)
For Each row As DataRow In ResultsTable.Rows
For Each item In row.ItemArray
sb.Append(item.ToString + ","c)
Response.Write(item.ToString + "\n")
Response.Write(vbNewLine)
Next
sb.Append(vbCr & vbLf)
Next
'Response.End()
If Bind Then
BindData(ResultsDataSet)
End If
End Sub
Binding Data:
I think this is a cause in the issue.
Private Sub BindData(ByVal InputDataSet As DataSet)
ResultsDataView = InputDataSet.Tables("Results").DefaultView
ResultsDataView.Sort = ViewState("SortExpression").ToString()
ResultsGridView.DataSource = ResultsDataView
ResultsGridView.DataBind()
End Sub
Reporting action:
This is where I am trying to use the table data. But it is showing as nothing.
Protected Sub ReportButton_Click(sender As Object, e As EventArgs) Handles ReportButton.Click
For Each row As DataRow In ResultsTable.Rows
For Each item In row.ItemArray
Response.Write(item.ToString)
Next
Next
End Sub
The reason I'm trying to loop through this data is to both display the data in a gridview on the main view as well as export the data to CSV. If there is a different way to export a SQL query to CSV, I'm open to any suggestions.
There has to be something I can do to get the data from the SQL query to persist through the ReportButton_Click method. I've tried copying the datatable, I've tried global variables, I've tried different methods of looping through the dataset. What am I missing?!
Thank you all in advance.
EDIT
Here is the Page_Load:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack Then
'set focus to postback control
Dim x As String = GetPostBackControlName(Page)
If Len(x) > 0 Then
x = x.Replace("$", "_")
SetFocus(x)
End If
End If
If Not IsPostBack Then
ResultsGridView.AllowPaging = False
'Enable Gridview sorting
ResultsGridView.AllowSorting = True
'Initialize the sorting expression
ViewState("SortExpression") = "ID DESC"
'Populate the Gridview
Search()
End If
End Sub
In your search function add this line after the ResultsTable setting
ResultsTable = ResultsDataSet.Tables(0)
Session("LastSearch") = ResultsTable
Then in your report click event handler recover your data from the Session variable
Protected Sub ReportButton_Click(sender As Object, e As EventArgs) Handles ReportButton.Click
ResultsTable = DirectCast(Session("LastSearch"), DataTable)
For Each row As DataRow In ResultsTable.Rows
For Each item In row.ItemArray
Response.Write(item.ToString)
Next
Next
End Sub
You need to read about ASP.NET Life Cycle and understand that every time ASP.NET calls your methods it creates a new instance of your Page class. Of course this means that global page variables in ASP.NET are not very useful.
Also consider to read about that Session object and not misuse it.
What is the difference between SessionState and ViewState?

Update From DataGridView to Database

Dim sb As New MySqlConnectionStringBuilder
sb.Server = Form1.hostname.Text
sb.UserID = Form1.rootuser.Text
sb.Password = Form1.rootpassword.Text
sb.Database = Form1.hostdb.Text
sb.Port = Form1.hostport.Text
Using connection As New MySqlConnection(sb.ConnectionString)
Try
connection.Open()
Dim adapter1 As New MySqlDataAdapter(TextBox1.Text, connection)
Dim cmdb1 = New MySqlCommandBuilder(adapter1)
Dim ds As New DataSet
Dim words As String() = TextBox1.Text.Split(New Char() {" "c})
Dim tablenamewords = (words(3))
adapter1.Update(ds, tablenamewords)
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
connection.Dispose()
End Try
End Using
It's giving me this error:
Update unable to find TableMapping['creature_template'] or DataTable 'creature_template'.
I want to select items then use a DataGrid to update them.
Note: tablenamewords = "creature_template"
You can solve this in alot of different methods.
I prefer to update the DB with a single query every time the the user ends editing a cell.
BUT FIRST you have to bind a source to your DataGridView!
How to bind a source:
Go to your application design an click on your DataGridView
Click on the pause/start like little button as shown:
Click on the "ComboBox" like textbox labeled as "chose data source" as shown and click on it:
It will open a "form", click on the Add data source as shown:
Follow the wizard, you can do it without any furhter explanation!
Well done, you almost completed it. Just go in your code, and look for this sub:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.your_table_nameTableAdapter.Fill(Me.your_db_nameDataSet.your_table_name)
End Sub
The line inside your Form1_Load Sub will upload the data inside your DataGridView, leave it there if you want it to load with the form or cut/paste it wherever you like.
Now you can add this the code to programmatically update the DB:
Private Sub DataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
Try
Dim location As Point = DataGridView1.CurrentCellAddress
Dim sqlCmd As String = "UPDATE table_name SET " & _
DataGridView1.Columns(location.X).Name.Replace("DataGridViewTextBoxColumn", "") & " = #Data " & _
"WHERE " & _
DataGridView1.Columns(0).Name.Replace("DataGridViewTextBoxColumn", "") & " = #ID"
Using myConn As New SqlConnection(My.Settings.VISURE_DA_PDFConnectionString)
myConn.Open()
Using myCmd As New SqlCommand(sqlCmd, myConn)
myCmd.Parameters.Add("#Data", SqlDbType.VarChar)
myCmd.Parameters.Add("#ID", SqlDbType.Int)
myCmd.Parameters("#Data").Value = DataGridView1.Rows(location.Y).Cells(location.X).Value
myCmd.Parameters("#ID").Value = DataGridView1.Rows(0).Cells(location.X).Value
myCmd.ExecuteNonQuery()
End Using
myConn.Close()
End Using
Catch ex As Exception
Err.Clear()
End Try
End Sub
Remarks:
location.X is the col index, location.Y is the row index
DataGridView1.Columns(0).Name This is my ID (primary key) and it is always in the first column. Change it with yours.
Don't forget to add .Replace("DataGridViewTextBoxColumn", "") whan you are getting your column name
As previously said, this code will update your DB every time the user edits one cell on your DataGridView updating only the edited cell. This is not a big issue because if you want to edit two ore more cell, every time you leave an edited cell the method DataGridView1_CellEndEdit is fired!

How to use DataGridView and a button to delete a SQL entry in my DataGridView

So I've got my SQL connection setup and working and it pulls and binds the data to the datagridview. I have an update button that pushes the edited data back to the SQL server.
Private Sub DeleteButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles DeleteButton.Click
'Delete Current Cell Data
Dim deleteCmd As String = "Delete FROM Contacts WHERE au_id = #Id;"
Dim myCommand As SqlCommand = New SqlCommand(deleteCmd)
myCommand.Parameters.Add(New SqlParameter("#Id", SqlDbType.VarChar, 11))
'Start the SqlCommand "#Id" parameter to the ID of the row that was clicked.
myCommand.Parameters("#Id").Value = DataGridView1.SelectedCells
Now I am currently working on getting a delete button to function. Basically I need it to Delete the row of data that is currently selected.
Private Sub DeleteButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles DeleteButton.Click
If DataGridView1.SelectedRows.Count > 0 Then
'you may want to add a confirmation message, and if the user confirms delete
DataGridView1.Rows.Remove(DataGridView1.SelectedRows(0))
Else
MessageBox.Show("Select 1 row before you hit Delete")
End If
End Sub
This is what I came up with! I was going about it all wrong attempting to do it via SQL queries. Just needed to do it locally and then use my update button to finish the changes. Which will probably be safer given that end users are end users.

VB forms run time error, Adding columns to a Data Table

Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
Dim itemno As String
Dim quantity, count As Integer
count = count + 1
itemno = TextBox5.Text
Quantity = TextBox6.Text
sql = ("SELECT ItemNo ,DishName, DishPrice FROM tblMenuInfo WHERE ItemNo = """ & itemno & """")
da = New OleDb.OleDbDataAdapter(sql, Conn)
da.Fill(dsorder, "OrderInfo")
If count = 1 Then
dsorder.Tables("OrderInfo").Columns.Add("Quantity")
dsorder.Tables("OrderInfo").Columns.Add("Sub total")
End If
DataGridView1.DataSource = dsorder.Tables("OrderInfo")
DataGridView1.AutoResizeColumns()
End Sub
Hi, I'm currently doing a ordering system project in school and am fairly new with VB forms
i have an access table called tblMenuInfo with the columns ItemNo, DishName, DishPrice.
I'm trying to add a column to my data table called Sub Total and Quantity. But I get the following error message
{"A column named 'Quantity' already belongs to this DataTable."}
(Sorry I couldn't provide a print screen, I'm on a school computer)
My program only crashes on the second click.
Thanks In advance!
After your first click the datatable contains following columns
ItemNo|Dishname|Dishprice|Total|Quantity
If you click the second time, your datatable still contains those columns.
ItemNo|Dishname|Dishprice|Total|Quantity
When the code reaches the following point:
dsorder.Tables("OrderInfo").Columns.Add("Quantity")
The compiler says: "Hey i can't add that column! That column is already present in the datatable"
What you actually need to do: is check if the column is already present or clear the datatable of that dataset
Solution 1: Clear datatable after click
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
Dim itemno As String
Dim quantity, count As Integer
dsorder.Tables.Clear()
Note on solution 1: All data contained by the ds will be lost
Solution 2: Check if the column is present
'Check if datatable exists
If (dsorder.Tables("OrderInfo") IsNot Nothing) Then
'Check if column exists
If Not dsorder.Tables("OrderInfo").Columns.Contains("Quantity") Then
dsorder.Tables("OrderInfo").Columns.Add("Quantity")
dsorder.Tables("OrderInfo").Columns.Add("Sub total")
End If
End If

how do I refresh the textbox/datatable to re-run this command?

This piece of code grabs a customers hire record using their hire ID and displays their details in multiple textboxes. It all works fine and well, however, I can only run it once. If I type in another customers hire record ID it just displays the first customers details that were materialised, which I assume is because the datatable has been populated and not refreshed based on the new hire record ID I've entered.
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
Dim hirerecord1 As Integer = TextBox13.Text
Dim cmd2 As New SqlCommand("SELECT * FROM HireItemRecord WHERE HireRecord_Id = " & hirerecord1, cnn)
Dim sqlDa As New SqlDataAdapter(cmd2)
sqlDa.Fill(dt1)
If dt1.Rows.Count > 0 Then
TextBox14.Text = dt1.Rows(0)("RentalItem_Id").ToString()
TextBox15.Text = dt1.Rows(0)("HireRecord_Id").ToString()
TextBox45.Text = dt1.Rows(0)("HireItemBeginDate").ToString()
End If
cnn.Close()
End Sub
I'm not quite sure what to do to fix this...
Also, I'm having a similar problem with this..
Private Sub TextBox46_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox46.TextChanged
Dim keywords2 As String = TextBox46.Text
ds1.Tables("PersonDetails").DefaultView.RowFilter = "Last_Name like '%" & keywords2 & "%' "
End Sub
With this I can search a column of a datagridview for a match. It works all fine and well, until I insert a new record into the database at which point I refresh the datagridview to display the newly added record. After I do this, I can no longer search using the textbox. Once again, I'm not quite sure what to do to fix this issue.
Thank you very much for your help.
You're closing your connection at the end of the Button6_Click method and I can't see where it gets opened again. That would fit with your symptoms of the method only running successfully once. Have you tried to step through the code to see where it fails the second time?