apparent bug when repopulating a datagridview - vb.net

I have a created a simple example to illustrate what I have found. I also have a "fix", but I don't think I should need it!
I am using VS2010 and .NET 4. My form has a DataGridView (dgvTest), and a checkbox (CheckBox1). I am selecting 2 or 3 fields from a table, depending on whether the checkbox is checked (which it is initially).
My possible SQL statements are "SELECT ID,strForenames,strSurname FROM tblAlumni" and "SELECT strForenames,strSurname FROM tblAlumni".
I have used SQL Profiler to confirm that these are the queries sent to the DB.
All seems well when I load the form (I see 3 fields, in the order I expect), and when I uncheck the box (I see 2 fields, in the order I expect).
However, when I check it again, the ID field appears THIRD in the columns of the DataGridView, not first!
I have found a couple of reports of something similar to this (mis)behaviour on the Net, but folks just seem to find some other way to do the job rather than ask is this a problem with DataGridView that needs fixed.
Since I have been able to recreate it with a simple example I have some confidence (only some!) that I am not missing anything obvious.
Imports System.Data.SqlClient
Imports System.Windows.Forms
Imports System
Public Class Form1
Inherits System.Windows.Forms.Form
Dim sqlConn As SqlConnection
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
loadGRID()
End Sub
Private Sub loadGRID()
Dim sqlConn As SqlConnection = New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=aspnetdb;Integrated Security=True")
sqlConn.Open()
Dim dataAdapter As SqlDataAdapter = New SqlDataAdapter("SELECT " & IIf(CheckBox1.Checked, "ID,", "") & "strForenames,strSurname FROM tblAlumni", sqlConn)
Dim ds As DataSet = New DataSet()
dataAdapter.Fill(ds)
dgvTest.DataSource = ds.Tables(0)
sqlConn.Close()
End Sub
Private Sub CheckBox1_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
loadGRID()
End Sub
End Class
So my question is, do your experts agree this is a bug? The "fix" is to wipe the DataGridView between repopulations, but I'm not sure I should have to?
dgvTest.DataSource = Nothing
dgvTest.Refresh()

I have found a BindingSource as a glue between the 'datasource' and the datagridview works very nicely for me, sorry I know that doesn't answer whether this is a bug as I am not sure.
(c#)
BindingSource bindingSource = new BindingSource();
bindingSource.DataSource = ds.Tables(0);
bindingSource.ResetBindings(false);

However, when I check it again, the ID field appears THIRD in the columns of the DataGridView, not first!
Thats the expected behaviour as the columns strForenames and strSurname already exist.
Try dgvTest.Columns.Clear() before and dgvTest.refresh after changing the datasource

Related

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.

Autofill TextBox/Checkbox from a previous TextBox' value (VB.NET Database)

Note: I'm using Visual Studio, original work was on SQL Server, moved to VB.NET
I have a Textbox "ViewStatusTxt", next to it there's a Button "ViewStatusBtn"
Below it there's a TextBox "ViewNAMETxt", another TextBox "ViewACTIVITYTxt" and then a Checkbox "ModifyStatusCB"
I'm trying to auto-fill the Checkbox AND the Textbox based on the ID input there, however I really have no clue about it since I'm new to VB.NET
Here's the code used
Private Sub IDSearch(StatusViewBtn As String)
' ADD SEARCH QUERY PARAMETERS - WITH WILDCARDS
SQL.AddParam("#StatusViewBtn", StatusViewBtn)
'RUN QUERY - SEARCH GIVES THOSE RESULTS
SQL.ExecQuery(" SELECT
aID,
Name,
Status,
Activity
FROM
[dbo].[initialTable]
WHERE
aID = #StatusViewBtn
ORDER BY
aID ASC")
End Sub
That's the function's code, which is fully working since it's a smaller version of the same one I used in a Search Page
Here's the button's function, which I'm sure is where I'm having problems, unless I need to add a specific function to the ViewNAMETxt
Private Sub StatusViewBtn_Click(sender As Object, e As EventArgs) Handles StatusViewBtn.Click
IDSearch(StatusViewBtn.Text)
ViewNAMETxt.Text = SQL.ExecQuery("SELECT
Name
FROM
initialTable
WHERE
aID = #StatusViewBtn")
End Sub
And I haven't even started on the Checkbox, viewing how the first one caused me issues. Hopefully the solution would be similar to both of them.
Thanks for reading guys, and sorry for the newbie question
1- Suppose you have a table named YourTable(int KeyColumn, string StringColumn, boolean BooleanColumn)
2- Create a form and put 2 textboxes and a checkbox and a button on it. KeyColumnTextBox, StringColumnTextBox, BooelanColumnCheckBox, SearchButton
3- In click event handler for SearchButton put the codes:
Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click
Dim connection = New SqlConnection("Your Connection string here")
Dim command = New SqlCommand("SELECT StringColumn, BooleanColumn FROM YourTable WHERE KeyColumn=#KeyColumn", connection)
command.Parameters.Add(New SqlParameter("#KeyColumn", Int32.Parse(KeyColumnTextBox.Text)))
connection.Open()
Dim reader = command.ExecuteReader()
While reader.Read()
StringColumnTextBox.Text = reader.GetString(0)
BooleanColumnCheckBox.Checked = reader.GetBoolean(1)
End While
End Sub
Don't forget to Imports System.Data.SqlClient at top of your file.

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
}

How to manipulate the SQL Server database from grid view (Form Application in VB.NET)

I need to control a database from grid view.
In another article I have to see how to manipulate a database, but there still used textbox and button for next process. In my case I need to control the data from grid view, so tell me please if you have solution for this problem.
Specifications:
application form
visual basic .NET 2010
SQL Server database
A quick search online found this: link. Below is the example code from that link showing how to display data.
If you want to do CRUD, please take a look at the Microsoft example here.
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="Your .mdb path";"
Dim sql As String = "SELECT * FROM Authors"
Dim connection As New OleDbConnection(connectionString)
Dim dataadapter As New OleDbDataAdapter(sql, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "Authors_table")
connection.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Authors_table"
End Sub
End Class

How to color Grid cells in Grid View?

Below is my code and I have been trying to color the cells but not sure how to use the "Style" property when my source for grid is a DB. I am new to this so having difficulties getting started.
Some website or pointers would help a lot.
I want to be able to color some background cells or also color some rows or specific columns...Basically everything color related. How can I do this with my current snippet? Also a link to where I can learn more would be appreciated.
LarsTech I am trying to add you to a chat but I dont have enough rep so I think I can't contact you due to that.
Imports System.Data.SqlClient
Imports System.Collections.Generic
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connectionString As String = "data source=SQst; database=MVar2; User ID=Wepp; Password=2010Live; Integrated Security=false;"
Dim sql As String = "SELECT * FROM Prer"
Dim connection As New SqlConnection(connectionString)
Dim dataadapter As New SqlDataAdapter(sql, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "Authors_table")
connection.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Authors_table"
**DataGridView1.Rows[2].DefaultCellStyle.BackColor = Color.PaleGreen
DataGridView1.Rows[3].Cells[1].Style.BackColor = Color.Red**
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Call PrintDGV.Print_DataGridView(DataGridView1)
End Sub
End Class
Errors I get:
Error 1 Property access must assign to the property or use its value.
Error 2 Identifier expected.
Error 3 Property access must assign to the property or use its value.
Error 4 Identifier expected.
I tried:
DataGridView1.Rows(0).Cell(0).Style.BackColor = Color.Red
and I got 1 error:
Error 1 'Cell' is not a member of 'System.Windows.Forms.DataGridViewRow'.
EDIT: After looking more around the web I got to color selected cells using below code:
DataGridView1.Item(4, 5).Style.BackColor = Color.Red
This however doesn't color rows or columns so I am still looking to make those things work.
There are a few different ways of doing this. I beliebe that currentcell refers to the current active cell, so coloring based on that after filling your grid will yield no results.
A few ways to do this are:
c#:
For rows/cells:
dataGridView1.Rows[RowNumber].DefaultCellStyle.BackColor = Color.PaleGreen;
dataGridView1.Rows[RowNumber].Cells[1].Style.BackColor = Color.Red;
for columns:
dataGridView1.Columns[ColumnNumber].DefaultCellStyle.BackColor = Color.Black;
VB:
DataGridView1.Rows(0).DefaultCellStyle.BackColor = Color.Green
DataGridView1.Columns(0).DefaultCellStyle.BackColor = Color.Blue
Both of these will apply color to the cell background. Use some logic in order to control how/which cells/rows are being colored.
You can also set this declaritively in the .aspx file. The link is to a 2.0 version of the code, but this is still compatible.
MSDN