Updating Datagridview?
Hello! I'm trying to figure out how to update my a row in my DataGridView. As you can see in my codes, I basically just remade my INSERT statement and changed it to UPDATE. I'm aware of this and I knew it wouldn't work, but how can I update my datagridview?
Any help will be greatly appreciated!
Imports System.Data.OleDb
Public Class AdmMain
Dim con As New OleDbConnection
Sub fillcombo()
strsql = " select yrgr from yearandgrade"
Dim acscmd As New OleDb.OleDbCommand
acscmd.CommandText = strsql
acscmd.Connection = acsconn
acsdr = acscmd.ExecuteReader
While (acsdr.Read())
cboyr.Items.Add(acsdr("yrgr"))
End While
acscmd.Dispose()
acsdr.Close()
End Sub
Sub comb2()
strsql = " select sections from sectio"
Dim acscmd As New OleDb.OleDbCommand
acscmd.CommandText = strsql
acscmd.Connection = acsconn
acsdr = acscmd.ExecuteReader
While (acsdr.Read())
cbosec.Items.Add(acsdr("sections"))
End While
acscmd.Dispose()
acsdr.Close()
End Sub
Private Sub LinkLabel1_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
If MessageBox.Show("Are you sure you want to logout?", "Logout", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
MessageBox.Show("You have successfully logged out of VCM's Library Information System!", "Logout Confirmed")
Me.Close()
LoginUser.Show()
End If
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Me.TxtID.Text = ""
Me.txtFName.Text = ""
Me.txtMName.Text = ""
Me.txtLName.Text = ""
Me.cboyr.Text = ""
Me.cbosec.Text = ""
Me.TxtID.Focus()
End Sub
Private Sub AdmMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Module1.connect()
Me.fillcombo()
Me.comb2()
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Thesis\Thesis\Database1.accdb"
con.Open()
datagridshow()
End Sub
Private Sub datagridshow()
Dim ds As New DataSet
Dim dt As New DataTable
ds.Tables.Add(dt)
Dim da As New OleDbDataAdapter
da = New OleDbDataAdapter("select * from students ", con)
da.Fill(dt)
DataGridView1.DataSource = dt.DefaultView
con.Close()
End Sub
Private Sub btnAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnAdd.Click
Dim rbdtext As String = cboyr.SelectedItem.ToString
Dim uno As String = cbosec.SelectedItem.ToString
Try
Dim cnString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Thesis\Thesis\Database1.accdb"
Dim sqlquery As String = "INSERT INTO students " & _
"(StudentID, FirstName,MiddleName,LastName,Yr, [Section]) " & _
"VALUES (@studid, @fname,@mname,@lname,@yr, @sec)"
' Use this form to initialize both connection and command to
' avoid forgetting to set the appropriate properties....
Using conn = New System.Data.OleDb.OleDbConnection(cnString)
Using cmd = New System.Data.OleDb.OleDbCommand(sqlquery, conn)
conn.Open()
cmd.Parameters.AddWithValue("@studid", TxtID.Text)
cmd.Parameters.AddWithValue("@fname", txtFName.Text)
cmd.Parameters.AddWithValue("@mname", txtMName.Text)
cmd.Parameters.AddWithValue("@lname", txtLName.Text)
cmd.Parameters.AddWithValue("@yr", rbdtext)
cmd.Parameters.AddWithValue("@sec", uno)
If TxtID.Text = "" Or txtFName.Text = "" Or txtMName.Text = "" Or txtLName.Text = "" Or cboyr.SelectedIndex = -1 Or cbosec.SelectedIndex = -1 Then
MessageBox.Show("Please complete the required fields.", "Admin", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Return
Else
Dim rowsInserted = cmd.ExecuteNonQuery()
If rowsInserted > 0 Then
MessageBox.Show("One record successfully added!", "Added!")
datagridshow()
Else
MessageBox.Show("Failure to add new record!", "Failure!")
End If
End If
End Using
End Using
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub TxtID_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TxtID.KeyPress
'97 - 122 = Ascii codes for simple letters
'65 - 90 = Ascii codes for capital letters
'48 - 57 = Ascii codes for numbers
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
End Sub
Private Sub btnEdit_Click(sender As System.Object, e As System.EventArgs) Handles btnEdit.Click
Dim rbdtext As String = cboyr.SelectedItem.ToString
Dim uno As String = cbosec.SelectedItem.ToString
Try
Dim cnString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Thesis\Thesis\Database1.accdb"
Dim sqlquery As String = "UPDATE students SET" & _
"(StudentID, FirstName,MiddleName,LastName,Yr, [Section]) " & _
"VALUES (@studid, @fname,@mname,@lname,@yr, @sec)"
' Use this form to initialize both connection and command to
' avoid forgetting to set the appropriate properties....
Using conn = New System.Data.OleDb.OleDbConnection(cnString)
Using cmd = New System.Data.OleDb.OleDbCommand(sqlquery, conn)
conn.Open()
cmd.Parameters.AddWithValue("@studid", TxtID.Text)
cmd.Parameters.AddWithValue("@fname", txtFName.Text)
cmd.Parameters.AddWithValue("@mname", txtMName.Text)
cmd.Parameters.AddWithValue("@lname", txtLName.Text)
cmd.Parameters.AddWithValue("@yr", rbdtext)
cmd.Parameters.AddWithValue("@sec", uno)
If TxtID.Text = "" Or txtFName.Text = "" Or txtMName.Text = "" Or txtLName.Text = "" Or cboyr.SelectedIndex = -1 Or cbosec.SelectedIndex = -1 Then
MessageBox.Show("Please complete the required fields.", "Admin", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Return
Else
Dim rowsInserted = cmd.ExecuteNonQuery()
If rowsInserted > 0 Then
MessageBox.Show("One record successfully updated!", "Updated!")
datagridshow()
Else
MessageBox.Show("Failure to update new record!", "Failure!")
End If
End If
End Using
End Using
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
Here's the error that shows up when I try to click my edit button.
I followed exactly what you and @pvdg42 said but It still wouldn't work. Here's my new code.
Private Sub btnEdit_Click(sender As System.Object, e As System.EventArgs) Handles btnEdit.Click
Dim rbdtext As String = cboyr.SelectedItem.ToString
Dim uno As String = cbosec.SelectedItem.ToString
Try
Dim cnString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Thesis\Thesis\Database1.accdb"
Dim sqlquery As String = "UPDATE Students SET StudentID = @STUDID, FirstName = @FNAME, MiddleName = @MNAME, LastName= @LNAME, Yr = @YRR, Section = @SEC WHERE StudentID = @STUDID, FirstName =@FNAME, MiddleName = @MNAME, LastName= @LNAME, Yr = @YRR, Section = @SEC"
' Use this form to initialize both connection and command to
' avoid forgetting to set the appropriate properties....
Using conn = New System.Data.OleDb.OleDbConnection(cnString)
Using cmd = New System.Data.OleDb.OleDbCommand(sqlquery, conn)
conn.Open()
cmd.Parameters.AddWithValue("@STUDID", TxtID.Text)
cmd.Parameters.AddWithValue("@FNAME", txtFName.Text)
cmd.Parameters.AddWithValue("@MNAME", txtMName.Text)
cmd.Parameters.AddWithValue("@LNAME", txtLName.Text)
cmd.Parameters.AddWithValue("@YRR", rbdtext)
cmd.Parameters.AddWithValue("@SEC", uno)
If TxtID.Text = "" Or txtFName.Text = "" Or txtMName.Text = "" Or txtLName.Text = "" Or cboyr.SelectedIndex = -1 Or cbosec.SelectedIndex = -1 Then
MessageBox.Show("Please complete the required fields.", "Admin", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Return
Else
Dim rowsInserted = cmd.ExecuteNonQuery()
If rowsInserted > 0 Then
MessageBox.Show("One record successfully updated!", "Updated!")
datagridshow()
Else
MessageBox.Show("Failure to update new record!", "Failure!")
End If
End If
End Using
End Using
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Btw, I've set my datagridview's select to a full row select and I want my system to update (by changing the information on the textbox and combobox) by clicking the button a row if I selected them. How do I do I make this possible? Thanks for the reply!
Similar Messages
-
Update Access database via OleDB from DataGridView
I have been scouring these forums and the internet in general as well as doing a lot of reading, all to no avail. I can not seem to successfully update the Access database from an edited DataGridView. I am trying to use Stored Procedures that
are in the Access database and work fine therein. The DGV is filled in properly. I have tried an ever-increasing number of variants to update the database (Private Sub BtnUpdate...) without success. I'd really, really appreciate some
guidance here.
Here is my code thus far:
Public Class Form1
Dim con As OleDbConnection
Dim cmd As OleDbCommand
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim ProviderConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
Dim TargetList As String = "C:\Users\Administrator\Documents\Visual Studio 2010\Projects\Development5\Test.mdb"
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'establish a connection to the database
con = New OleDbConnection(ProviderConnectionString & TargetList)
con.Open()
'define the command to be used
cmd = New OleDbCommand
cmd.Connection = con
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "ListAllTargets"
'create the data adapter based on the command
da = New OleDbDataAdapter(cmd)
'fill the data set based on the command
ds = New DataSet
da.Fill(ds, "AllTargets")
'bind and load dgvTargets with the data
dgvTargetList.DataSource = ds.Tables("AllTargets") ' Binding to dgvtargetlist
End Sub
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
da.UpdateCommand = New OleDbCommand("UPDATE TargetList SET;", con)
Validate()
da.Update(ds.Tables("AllTargets"))
Me.ds.AcceptChanges()
End Sub
End ClassHi John,
Welcome to MSDN forums!
Cor pointed you to the right direction. An OleDBCommandbuilder object is required, which can be used to automatically
generate DeleteCommand, UpdateCommand and InsertCommand for DataAdapter object.
Here is detailed walkthrough: How to update
(Insert/Update/Delete) data back into MS Access database from DataGridView.
1) New a WinForms project, drag&drop DataGridView1 and Button1 onto
Form1.
2) Add database file test.mdb to project via: Data menu -> Add New Data Source
Wizard ... then you can use ralative path to this database file in code
3) Select/click
your database file test.mdb in Solution Explorer
-> Properties Pane
-> change the "copy to ouput directory" to "copy
if newer"
4) Code sample
Imports System.Data.OleDb
Public
Class Form1
Dim myDA As OleDbDataAdapter
Dim myDataSet As DataSet
Private Sub Form1_Load(ByVal sender
As System.Object, ByVal e
As System.EventArgs) Handles
MyBase.Load
Dim con As OleDbConnection =
New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;data source=|DataDirectory|\test.mdb") ' Use relative path to database file
Dim cmd As OleDbCommand =
New OleDbCommand("SELECT * FROM Table1", con)
con.Open()
myDA = New OleDbDataAdapter(cmd)
'Here one CommandBuilder object is required.
'It will automatically generate DeleteCommand,UpdateCommand and InsertCommand for DataAdapter object
Dim builder As OleDbCommandBuilder =
New OleDbCommandBuilder(myDA)
myDataSet = New DataSet()
myDA.Fill(myDataSet, "MyTable")
DataGridView1.DataSource = myDataSet.Tables("MyTable").DefaultView
con.Close()
con = Nothing
End Sub
' Save data back into database
Private Sub Button1_Click(ByVal sender
As System.Object, ByVal e
As System.EventArgs) Handles Button1.Click
Me.Validate()
Me.myDA.Update(Me.myDataSet.Tables("MyTable"))
Me.myDataSet.AcceptChanges()
End Sub
End
Class
Best regards,
Martin Xie
MSDN Subscriber
Support in Forum
If you have any feedback on our support, please contact
[email protected]
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Welcome to the All-In-One Code Framework! If you have any feedback, please tell us. -
C# load xml data with attributes to datagridview; update data and save back to the xml
Hi guys,
i currently have this XML as data
<DEALS>
<DEAL ID="22" ISBN="0-7888-1623-3" Screenplay="Mary Kaplan" Title ="Mr Gentleman" Director = "Jonathan Jones">
<ALLOCATION DEMANDE="5000" CODE="72" PRICE="25.00">2500</ALLOCATION>
<ALLOCATION DEMANDE="7000" CODE="75" PRICE="35.00">4000</ALLOCATION>
</DEAL>
<DEAL ID="23" ISBN="1-7988-1623-3" Screenplay="Joe Doe" Title ="Nothing Much" Director = "Listentome">
<ALLOCATION DEMANDE="3300" CODE="72" PRICE="15.00">2500</ALLOCATION>
</DEAL>
</DEALS>
I load the data with the code below:
i use xDocument to load the DealData.xml and then put it in ToString.
//outside of the form
public static class XElementExtensions
public static DataTable ToDataTable(this XElement element)
DataSet ds = new DataSet();
string rawXml = element.ToString();
ds.ReadXml(new StringReader(rawXml));
return ds.Tables[0];
public static DataTable ToDataTable(this IEnumerable<XElement> elements)
return ToDataTable(new XElement("Root", elements));
//in the form
private void button2_Click(object sender, EventArgs e)
var xDocument = XDocument.Load("DealData.xml");
string txtxml = xDocument.ToString();
StringReader reader = new StringReader(txtxml);
XDocument doc1 = XDocument.Load(reader);
var res = doc1.Descendants("DEAL").ToList().Where(x => x.Attribute("ID").Value == "22").Descendants("ALLOCATION");
dataGridView1.DataSource = res.ToDataTable();
Now my question is:
I would like to update the data from the DataGridview with the Attribute("ID").Value == "22" and save the data back to the XML.
For example, after I load my data on the datagridview, we only pickup anything that is in the node
<DEAL ID="22" ISBN="0-7888-1623-3" Screenplay="Mary Kaplan" Title ="Mr Gentleman" Director = "Jonathan Jones">
<ALLOCATION DEMANDE="5000" CODE="72" PRICE="25.00">2500</ALLOCATION>
<ALLOCATION DEMANDE="7000" CODE="75" PRICE="35.00">4000</ALLOCATION>
</DEAL>
I updated the datagridview below with DEMANDE = 9000 CODE = 66 PRICE = 24.77 AND ALLOCATION = 1200
I want be able to extract the data back in the xml as a child of the DEAL ID = "22"
So that the XML file looks like this
<DEALS>
<DEAL ID="22" ISBN="0-7888-1623-3" Screenplay="Mary Kaplan" Title ="Mr Gentleman" Director = "Jonathan Jones">
<ALLOCATION DEMANDE="5000" CODE="72" PRICE="25.00">2500</ALLOCATION>
<ALLOCATION DEMANDE="7000" CODE="75" PRICE="35.00">4000</ALLOCATION>
<ALLOCATION DEMANDE="9000" CODE="66" PRICE="24.77">1200</ALLOCATION> <-! this is the new line !->
</DEAL>
<DEAL ID="23" ISBN="1-7988-1623-3" Screenplay="Joe Doe" Title ="Nothing Much" Director = "Listentome">
<ALLOCATION DEMANDE="3300" CODE="72" PRICE="15.00">2500</ALLOCATION>
</DEAL>
</DEALS>
Is there a way to achieve that?
I have been searching and reading in the books but i cannot find a solution for this.
Thank you
Please do not forget to click “Vote as Helpful” if the reply helps/directs you toward your solution and or "Mark as Answer" if it solves your question. This will help to contribute to the forum.I would think of something like the below, the id is passed as static you need to change this
protected virtual void button1_Click(object sender, EventArgs e)
//Get DataTable from DGV datasource
DataTable dt = new DataTable();
dt = (DataTable)dataGridView1.DataSource;
string file1 = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><DEALS><DEAL ID=\"22\" ISBN=\"0-7888-1623-3\" Screenplay=\"Mary Kaplan\" Title =\"Mr Gentleman\" Director = \"Jonathan Jones\"><ALLOCATION DEMANDE=\"5000\" CODE=\"72\" PRICE=\"25.00\">2500</ALLOCATION><ALLOCATION DEMANDE=\"7000\" CODE=\"75\" PRICE=\"35.00\">4000</ALLOCATION></DEAL><DEAL ID=\"23\" ISBN=\"1-7988-1623-3\" Screenplay=\"Joe Doe\" Title =\"Nothing Much\" Director = \"Listentome\"><ALLOCATION DEMANDE=\"3300\" CODE=\"72\" PRICE=\"15.00\">2500</ALLOCATION></DEAL></DEALS>";
StringReader reader = new StringReader(file1);
XDocument doc1 = XDocument.Load(reader);
//Remove all elements related to the id being populated into the Grid
doc1.Descendants("DEAL").ToList().Where(x => x.Attribute("ID").Value == "22").Descendants("ALLOCATION").Remove();
//loop through datatable and create new xelement to be added to the xdocument
foreach (DataRow dr in dt.Rows)
XElement xe = new XElement("ALLOCATION",
new XAttribute("DEMANDE", dr[0].ToString()),
new XAttribute("CODE", dr[1].ToString()),
new XAttribute("PRICE", dr[2].ToString()));
xe.Value = dr[3].ToString();
doc1.Descendants("DEAL").ToList().Where(x => x.Attribute("ID").Value == "22").FirstOrDefault().Add(xe);
Fouad Roumieh -
How to update record from datagridview
hi every one
am new in .net am developing an inventory system for learning.
i successfully develop a purchase form where user can put record for parching invoice.
as
and for save record am using flowing code.
Private Sub btn_Save_Click(sender As Object, e As EventArgs) Handles btn_Save.Click
Dim connectionStringdgv As String = "Data Source= ABDULLAH-PC;Initial Catalog=Erpdb;Persist Security Info=True;User ID=jabbar;Password=abc123"
Dim connection As New SqlClient.SqlConnection(connectionStringdgv)
Dim adaptor As New SqlClient.SqlDataAdapter
Dim adaptor1 As New SqlClient.SqlDataAdapter
Dim dataset As New DataSet()
Dim datasetmax As New DataSet()
Dim adaptor3 As New SqlClient.SqlDataAdapter
Dim adaptormax As New SqlClient.SqlDataAdapter
Dim dataset3 As New DataSet()
Dim dataset1 As New DataSet()
Dim cmdinsert As New SqlClient.SqlCommand
Dim cmdinsert1 As New SqlClient.SqlCommand
Dim cmduppurtable As New SqlClient.SqlCommand
Dim cmdupdrcrtable As New SqlClient.SqlCommand
Dim cmdinsert2 As New SqlClient.SqlCommand
Dim Cmd As New SqlClient.SqlCommand
Dim Commandmax As New SqlClient.SqlCommand
connection.Open()
cmdinsert1.Connection = connection
cmdinsert1.CommandText = "INSERT INTO purtrans(date,amount,paid,discount,[bill no],taxvalue,ac,tax)" _
& "VALUES ('" & DateTimePicker2.Text & "','" & GAmt.Text & "','" & amtpaid.Text & "','" & Tdis.Text & "','" & invo.Text &
"','" & ttax.Text & "','" & txtCode.Text & "','" & tv.Text & "')"
cmdinsert1.ExecuteNonQuery()
'find last id'
Commandmax.Connection = connection
Commandmax.CommandText = "SELECT date,MAX(sr) FROM purtrans GROUP BY date"
Commandmax.ExecuteNonQuery()
adaptormax.SelectCommand = Commandmax
Dim maxtable As New DataTable
adaptormax.SelectCommand = Commandmax
adaptormax.Fill(maxtable)
If maxtable.Rows.Count > 0 Then
SrTextBox.Text = maxtable.Select.Last.Item(1)
End If
If connection.State = ConnectionState.Open Then
connection.Close()
End If
connection.Close()
Dim n, m As Integer
n = Me.dgv.Rows.Count - 1
For m = 0 To n - 1
Dim cd As String = "insert Into amountdrcr(todate,ac,party1,amount,purtransid,qty,rate,billno,disc,tax,weight,sp,drcr) VALUES (@todate,@ac,@Party1,@amount,@purtransid,@qty,@rate,@billno,@disc,@tax,@Weight,'Purchase','Dr')"
Cmd = New SqlClient.SqlCommand(cd)
Cmd.Connection = connection
Cmd.Parameters.AddWithValue("todate", DateTimePicker2.Text)
Cmd.Parameters.AddWithValue("ac", dgv.Rows(m).Cells("itemcode").Value)
Cmd.Parameters.AddWithValue("party1", cmbname.Text)
Cmd.Parameters.AddWithValue("amount", dgv.Rows(m).Cells("Amount").Value)
Cmd.Parameters.AddWithValue("purtransid", SrTextBox.Text)
Cmd.Parameters.AddWithValue("Qty", dgv.Rows(m).Cells("Qty").Value)
Cmd.Parameters.AddWithValue("Rate", dgv.Rows(m).Cells("Rate").Value)
Cmd.Parameters.AddWithValue("BILLNO", invo.Text)
Cmd.Parameters.AddWithValue("Disc", dgv.Rows(m).Cells("Disc").Value)
Cmd.Parameters.AddWithValue("tax", txtPerVat.Text)
Cmd.Parameters.AddWithValue("Weight", dgv.Rows(m).Cells("Weight").Value)
connection.Open()
Cmd.ExecuteNonQuery()
connection.Close()
Next
MsgBox("Your Record save Sucssfully", vbOKOnly, "AANO TECH")
'posting a credit voucher for supplier'
If Balance.Text > 0 Then
Dim cd2 As String = "insert Into amountdrcr(todate,ac,party1,amount,purtransid,billno,sp,drcr) VALUES (@todate,@ac,@Party1,@amount,@purtransid,@Billno,'Purchase','Cr')"
cmdinsert2 = New SqlClient.SqlCommand(cd2)
cmdinsert2.Connection = connection
cmdinsert2.Parameters.AddWithValue("todate", DateTimePicker2.Text)
cmdinsert2.Parameters.AddWithValue("ac", txtCode.Text)
cmdinsert2.Parameters.AddWithValue("party1", cmbname.Text)
cmdinsert2.Parameters.AddWithValue("amount", Balance.Text)
cmdinsert2.Parameters.AddWithValue("purtransid", SrTextBox.Text)
cmdinsert2.Parameters.AddWithValue("billno", invo.Text)
connection.Open()
cmdinsert2.ExecuteNonQuery()
connection.Close()
dgv.Rows.Clear()
btn_Save.Enabled = False
invo.Text = ""
txtCode.Text = ""
TAmt.Text = ""
GAmt.Text = ""
Tdis.Text = ""
Balance.Text = ""
ttax.Text = ""
amtpaid.Text = ""
txtAddress.Text = ""
txtPhone.Text = ""
cmbname.Text = ""
btnAdd.Enabled = False
txtQty.Text = ""
Wk.Text = ""
txtRate.Text = ""
txtRate.Text = ""
txtPerDisc.Text = ""
txtPerVat.Text = ""
cmbItemCode.Text = ""
cmbitemname.Text = ""
invo.Focus()
Else
dgv.Rows.Clear()
btn_Save.Enabled = False
invo.Text = ""
txtCode.Text = ""
TAmt.Text = ""
GAmt.Text = ""
Tdis.Text = ""
Balance.Text = ""
ttax.Text = ""
amtpaid.Text = ""
txtAddress.Text = ""
txtPhone.Text = ""
cmbname.Text = ""
txtQty.Text = ""
Wk.Text = ""
txtRate.Text = ""
txtRate.Text = ""
txtPerDisc.Text = ""
txtPerVat.Text = ""
cmbItemCode.Text = ""
cmbitemname.Text = ""
btnAdd.Enabled = False
invo.Focus()
End If
what is the easiest way for editing record
please guide me thanks
Hi ABDULLAH,
>> what is the easiest way for editing record
What do you mean by “editing record” ? Do you mean that you want to update the record according the textboxes in the form? If so, I am afraid that there is no better way, you need to use the ado.net and the update command to achieve that like you insert
new records. If you want to modify the record in the datagridview directly, I think you could bind the dataset to the datagridview, and then modify the record in the datagridview, and then save the changes to the database. The link below might be useful to
you:
# DataGridview Update
https://social.msdn.microsoft.com/Forums/en-US/5980181e-f666-4f0a-ab50-c4ebecf96f02/datagridview-update-?forum=Vsexpressvb
Best Regards,
Edward
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click HERE to participate the survey. -
hello,everybody ,it a question makes me crazy .my code is that :
public string tableName = "";
public DataSet ds;
public OleDbDataAdapter myAdapter;
public string sql = "";
private void button12_Click_1(object sender, EventArgs e)
sql = textBox5.Text.Trim();
OleDbConnection Conn = new OleDbConnection(st_contractconn);
Conn.Open();
this.comboBox1.Items.Add(this.textBox5.Text);
try
System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"(?<=from\s)\w+(?=\s)");
System.Text.RegularExpressions.Match B = r.Match(sql);
tableName = B.ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM PT_PO",Conn);
Conn.Close();
myAdapter = new OleDbDataAdapter(cmd);
ds = new DataSet();
myAdapter.Fill(ds, "PT_PO");
dataGridView2.DataSource = ds.Tables["PT_PO"].DefaultView;
this.groupBox2.Text = "共查询到" + ds.Tables[0].Rows.Count.ToString() + "条记录" + tableName;
catch (Exception ex)
MessageBox.Show(ex.Message);
private void button26_Click(object sender, EventArgs e)
OleDbConnection Conn = new OleDbConnection(st_contractconn);
Conn.Open();
OleDbCommandBuilder Builder = new OleDbCommandBuilder(myAdapter);
Validate() ;
myAdapter.Update(ds.Tables["PT_PO"]);
Conn.Close();
ds.AcceptChanges() ;
when it run to the myAdapter.Update(ds.Tables["PT_PO"]); it comes out a wrong "对于不返回任何基表信息的 SelectCommand 不支持动态 SQL 生成。" who knows it is why ,my QQ is 501212848,thankyou very much.Hello,
We were a IBM-DB2 shop for over 20 years, when we moved to .NET we found it was better to use the native DB2 data provider which you can download from IBM for free.
Main objects
IBM.Data.DB2.iSeries.iDB2Connection
IBM.Data.DB2.iSeries.iDB2Command
IBM.Data.DB2.iSeries.iDB2Parameter
So you would not use adapters but write code using the key objects above. Then to get new primary keys we would use
SELECT nextval for SOMETABLE_REF_AUTONUMBER_SEQUENCE from sysibm.sysdummy1
Bottom line is the structure is create a connection, create a command, set the connection and command text along with creating parameters as needed.
Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.
what is the meaning about you ? db2 cannt using adapters to update the datebase? -
How to edit a datagridview/textboxes using tableadapters in c# and sql
I am wondering what is the best way to edit a database that has multiple tables.
(Section 1) I have a Administration, Teacher and Student table that is linked up with the Person table which has a Primary Key.
The Person table consists of the general information of the person.
The Student table consists of information about the student; student ID and qualification code.
The Teacher table consists of information about the teacher; teacher ID, Reg No and password.
The Administration table consists of information about the admin; admin ID, Role and password.
As the Primary Key in the Person table is the ID, I have linked up with each of the other's table with their appropriate ID.
(Section 2) I have a Course and Qualification table that is linked up with the Student and Teacher table as well as each other.
The course table constists of the Course ID, Course Name ... and Teacher ID.
The Qualifications table consists of Qualification Code, Qualification Name and Duration.
There is a section where I have to create a view which shows just the Student ID, Course ID and has the Student's Marks in it.
I have got a combobox which then links up with the dgv(datagridview).
I have got insert and delete methods for both sections. Here is an example of the insert method into the Admin/Person table.
try
personTableAdapter.Insert(aFirstName.Text, aSurname.Text, Convert.ToDateTime(aDoB.Text), aPhone.Text, aAdd1.Text, aAdd2.Text, aSuburb.Text, aState.Text, aPostcode.Text, AdminType.Text);
administrationTableAdapter.Insert(Convert.ToInt32(aAID1.Text), aRole.Text, aPassword.Text);
MessageBox.Show(aFirstName.Text + " " + aSurname.Text + " has been added. Your ID is " + aAID1.Text);
this.personTableAdapter.Fill(this._30002195DataSet.Person);
this.administrationTableAdapter.Fill(this._30002195DataSet.Administration);
catch (Exception ex)
MessageBox.Show(ex.Message);
Here is an example of the delete method in the Admin/Person table.
try
personTableAdapter.Delete(Convert.ToInt32(aID.Text), aFirstName.Text, aSurname.Text, Convert.ToDateTime(aDoB.Text), aPhone.Text, aAdd1.Text, aAdd2.Text, aSuburb.Text, aState.Text, aPostcode.Text, AdminType.Text);
administrationTableAdapter.Delete(Convert.ToInt32(aAID.Text), aRole.Text, aPassword.Text);
MessageBox.Show("Person Deleted");
this.personTableAdapter.Fill(this._30002195DataSet.Person);
this.administrationTableAdapter.Fill(this._30002195DataSet.Administration);
catch (Exception)
MessageBox.Show("Cannot delete Person");
Those methods above are working fine, what I'm having problems with, is with the editing/updating part.
I have tried a few things and haven't worked.
Here's an example of an edit, while trying to use textboxes.
personTableAdapter.Update(aFirstName.Text, aSurname.Text, Convert.ToDateTime(aDoB.Text), aPhone.Text, aAdd1.Text, aAdd2.Text, aSuburb.Text, aState.Text, aPostcode.Text, AdminType.Text, Convert.ToInt32(aID.Text), aFirstName.Text, aSurname.Text, Convert.ToDateTime(aDoB.Text), aPhone.Text, aAdd1.Text, aAdd2.Text, aSuburb.Text, aState.Text, aPostcode.Text, AdminType.Text);
administrationTableAdapter.Update(aRole.Text, aPassword.Text, Convert.ToInt32(aAID.Text), aRole.Text, aPassword.Text);
personBindingSource.EndEdit();
administrationBindingSource.EndEdit();
administrationTableAdapter.Update(_30002195DataSet.Administration);
personTableAdapter.Update(_30002195DataSet.Person);
MessageBox.Show("Person Updated");
this.personTableAdapter.Fill(this._30002195DataSet.Person);
this.administrationTableAdapter.Fill(this._30002195DataSet.Administration);
Here I tried to do the new values/original values, while trying to use textboxes
personTableAdapter.Update(aFirstName.Text, aSurname.Text, Convert.ToDateTime(aDoB.Text), aPhone.Text, aAdd1.Text, aAdd2.Text, aSuburb.Text, aState.Text, aPostcode.Text, AdminType.Text, Convert.ToInt32(aID.Text), aFirstName.Text, aSurname.Text, Convert.ToDateTime(aDoB.Text), aPhone.Text, aAdd1.Text, aAdd2.Text, aSuburb.Text, aState.Text, aPostcode.Text, AdminType.Text);
administrationTableAdapter.Update(aRole.Text, aPassword.Text, Convert.ToInt32(aAID.Text), aRole.Text, aPassword.Text);
Trying to use the example through the mdsn, this is trying to use the datagridview.
this.Validate();
personBindingSource.EndEdit();
teacherBindingSource.EndEdit();
_30002195DataSet.PersonDataTable deletedPerson = (_30002195DataSet.PersonDataTable)
_30002195DataSet.Person.GetChanges(DataRowState.Deleted);
_30002195DataSet.PersonDataTable newPerson = (_30002195DataSet.PersonDataTable)
_30002195DataSet.Person.GetChanges(DataRowState.Added);
_30002195DataSet.PersonDataTable modifiedPerson = (_30002195DataSet.PersonDataTable)
_30002195DataSet.Person.GetChanges(DataRowState.Modified);
try
if (deletedPerson != null)
personTableAdapter.Update(deletedPerson);
teacherTableAdapter.Update(_30002195DataSet.Teacher);
if (newPerson != null)
personTableAdapter.Update(newPerson);
if (modifiedPerson != null)
personTableAdapter.Update(modifiedPerson);
_30002195DataSet.AcceptChanges();
catch (System.Exception ex)
MessageBox.Show(ex.Message);
finally
if (deletedPerson != null)
deletedPerson.Dispose();
if (newPerson != null)
newPerson.Dispose();
if (modifiedPerson != null)
modifiedPerson.Dispose();
MessageBox.Show("Updated");
this.personTableAdapter.Fill(this._30002195DataSet.Person);
this.teacherTableAdapter.Fill(this._30002195DataSet.Teacher);
Now because I am trying to edit a certain user which requires the Person table along with the other table, it just doesn't seem to work at all.
With the datagridview, I made a new view in the sql and it has both tables combined and shows when I bring it out from the datasource, but where I go into the dataset builder and try to create an update method, all I get is the "Update" not what
I would get when I created the update method from just the person's table by itself.
Can someone provide me with an example or help me out someway because I am struggling with this, I can't seem to find much information at all.
Thanks.I have used the designer to create a new datagridview, when using that dgv it doesn't want to update to the relevent tables in my database. So say you have the person and admin dgv together and you need to update it, how would you get it to work
to the database? I did just end up using 2 seperate dgv's but it won't get accepted.
try
_30002195DataSetTableAdapters.PersonTableAdapter personTableAdapter = new _30002195DataSetTableAdapters.PersonTableAdapter();
// person table
_30002195DataSetTableAdapters.AdministrationTableAdapter administrationTableAdapter = new _30002195DataSetTableAdapters.AdministrationTableAdapter();
// admin table
ViewSetTableAdapters.AdminViewTableAdapter adminviewTableAdapter = new ViewSetTableAdapters.AdminViewTableAdapter();
// tried using this for both the admin/person tables together but didn't work?
this.Validate();
adminViewBindingSource.EndEdit(); //both
personBindingSource.EndEdit();
administrationBindingSource.EndEdit();
personTableAdapter.Update(_30002195DataSet.Person);
administrationTableAdapter.Update(_30002195DataSet.Administration);
MessageBox.Show("Updated");
this.personTableAdapter.Fill(this._30002195DataSet.Person);
this.administrationTableAdapter.Fill(this._30002195DataSet.Administration);
catch (Exception ex)
MessageBox.Show(ex.Message);
So, how would I write the code so it edits both the tables from just the one dgv?
Hello,
Based on these words above, it seems that the key issue is that you want to display and edit the data of two tables with a single datagridview, right? If so, I am afraid that I would recommend you consider using code other than designer to get that done.
Are these table store in the same database?
If so, then you could consider getting that done with ADO.NET, we could getting the data of multiple table with sql query. You could consider
using sql query to get all data from multiple tables
of database, and then fill them to a single datatable.
For query issue, you could consider getting help from
Transact-SQL forum.
If not, then we need to create update query for both table and execute these queries with sperate connection strings.
Regards,
Carl
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
Microsoft Visual Basic 2010 Express.
I am new to Visual Basic programing and i am trying to understand the relationships between Datasets, database, table Adaptors. I have to following code that is is giving me the following error" Unable to load, Update requires a valid DeleteCommand
when passed DataRow collection with deleted rows".
I can track the error and its located in "OffsetTableTableAdapter.Update(MaterionOffsetDataSet.OffsetTable)" code. What am i missing?
It seems that i can delete the data on the DataGridView Table and it only displays the correct data. but my database is not updating, even though the data grid displays differently.I can determine this because, when i save the offset database, i have all
the previous uploads and all the rows that i wanted to delete are still there.
My final goal is to be able to import offset data from a CSV file, save this data on the pc, send a copy of this data to a NuermicUpDown so the customer can modify certain numbers. From here they download all the date to a controller. IF the customer
needs to modify the imported data, they can go to a tab with a data grid view and modify the table. They will also have to option to save the modified data into a csv file.
Im not sure if i am making this overcomplicated or if there is a easier way to program this.
CODE:
Private Function LoadOffSetData()
Dim LoadOffsetDialog As New OpenFileDialog 'create a new open file dialog and setup its parameters
LoadOffsetDialog.DefaultExt = "csv"
LoadOffsetDialog.Filter = "csv|*.csv"
LoadOffsetDialog.Title = "Load Offset Data"
LoadOffsetDialog.FileName = "RollCoaterOffset.csv"
If LoadOffsetDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then 'show the dialog and if the result is ok then
Try
Dim myStream As New System.IO.StreamReader(LoadOffsetDialog.OpenFile) 'try to open the file with a stream reader
If (myStream IsNot Nothing) Then 'if the file is valid
For Each oldRow As MaterionOffsetDataSet.OffsetTableRow In MaterionOffsetDataSet.OffsetTable.Rows
oldRow.Delete()
'delete all of the existing rows
Next
'OffsetTableTableAdapter.Update(MaterionOffsetDataSet.OffsetTable)
Dim rowvalue As String
Dim cellvalue(25) As String
'Reading CSV file content
While myStream.Peek() <> -1
Dim NRow As MaterionOffsetDataSet.OffsetTableRow
rowvalue = myStream.ReadLine()
cellvalue = rowvalue.Split(","c) 'check what is ur separator
NRow = MaterionOffsetDataSet.OffsetTable.Rows.Add(cellvalue)
Me.OffsetTableTableAdapter.Update(NRow)
End While
Me.OffsetTableTableAdapter.Update(MaterionOffsetDataSet.OffsetTable)
MainOffset.Value = OffsetTableTableAdapter.MainOffsetValue 'saves all the table offsets
to the offset numericUpDown registers in the main window
StationOffset01.Value = OffsetTableTableAdapter.Station01Value
StationOffset02.Value = OffsetTableTableAdapter.Station02Value
myStream.Close() 'close the stream
Return True
Else 'if we were not able to open the file then
MsgBox("Unable to load, check file name and location") 'let the operator know that the file wasn't able to open
Return False
End If
Catch ex As Exception
MsgBox("Unable to load, " + ex.Message)
Return False
End Try
Else
Return False
End If
End FunctionHello SaulMTZ,
>>I can track the error and its located in "OffsetTableTableAdapter.Update(MaterionOffsetDataSet.OffsetTable)" code. What am i missing?
This error usually shows that you do not initialize the
DeleteCommand object, you could check this
article to see if you get a workaround.
>> Im not sure if i am making this overcomplicated or if there is a easier way to program this.
If you are working CSV file, you could use OleDB to read it which would treat the CSV file as a Table:
http://www.codeproject.com/Articles/27802/Using-OleDb-to-Import-Text-Files-tab-CSV-custom
which seems to be easier (in my opinion).
Regards.
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
How to have custom control in DataGridView display object's value?
I have a sample project located
here
The project has a main form `Form1` where the user can enter customers in a datagridview. The `CustomerType` column is a custom control and when the user clicks the button, a search form `Form2` pops up.
The search form is populated with a list of type `CustomerType`. The user can select a record by double-clicking on the row, and this object should be set in the custom control. The `DataGridView` should then display the `Description` property but in the background
each cell should hold the value (ie. the `CustomerType` instance).
The relevant code is located in the following classes:
The column class:
public class DataGridViewCustomerTypeColumn : DataGridViewColumn
public DataGridViewCustomerTypeColumn()
: base(new CustomerTypeCell())
public override DataGridViewCell CellTemplate
get { return base.CellTemplate; }
set
if (value != null && !value.GetType().IsAssignableFrom(typeof(CustomerTypeCell)))
throw new InvalidCastException("Should be CustomerTypeCell.");
base.CellTemplate = value;
The cell class:
public class CustomerTypeCell : DataGridViewTextBoxCell
public CustomerTypeCell()
: base()
public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle);
CustomerTypeSearch ctl = DataGridView.EditingControl as CustomerTypeSearch;
if (this.Value == null)
ctl.Value = (CustomerType)this.DefaultNewRowValue;
else
ctl.Value = (CustomerType)this.Value;
public override Type EditType
get { return typeof(CustomerTypeSearch); }
public override Type ValueType
get { return typeof(CustomerType); }
public override object DefaultNewRowValue
get { return null; }
And the custom control:
public partial class CustomerTypeSearch : UserControl, IDataGridViewEditingControl
private DataGridView dataGridView;
private int rowIndex;
private bool valueChanged = false;
private CustomerType value;
public CustomerTypeSearch()
InitializeComponent();
public CustomerType Value
get { return this.value; }
set
this.value = value;
if (value != null)
textBoxSearch.Text = value.Description;
else
textBoxSearch.Clear();
private void buttonSearch_Click(object sender, EventArgs e)
Form2 f = new Form2();
DialogResult dr = f.ShowDialog(this);
if (dr == DialogResult.OK)
Value = f.SelectedValue;
#region IDataGridViewEditingControl implementation
public object EditingControlFormattedValue
get
if (this.value != null)
return this.value.Description;
else
return null;
set
if (this.value != null)
this.value.Description = (string)value;
public object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context)
return EditingControlFormattedValue;
public void ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle)
this.BorderStyle = BorderStyle.None;
this.Font = dataGridViewCellStyle.Font;
public int EditingControlRowIndex
get { return rowIndex; }
set { rowIndex = value; }
public bool EditingControlWantsInputKey(Keys key, bool dataGridViewWantsInputKey)
return false;
public void PrepareEditingControlForEdit(bool selectAll)
//No preparation needs to be done
public bool RepositionEditingControlOnValueChange
get { return false; }
public DataGridView EditingControlDataGridView
get { return dataGridView; }
set { dataGridView = value; }
public bool EditingControlValueChanged
get { return valueChanged; }
set { valueChanged = value; }
public Cursor EditingPanelCursor
get { return base.Cursor; }
#endregion
private void CustomerTypeSearch_Resize(object sender, EventArgs e)
buttonSearch.Left = this.Width - buttonSearch.Width;
textBoxSearch.Width = buttonSearch.Left;
However, the `DataGridView` is not displaying the text and it also is not keeping the `CustomerType` value for each cell.
What am I missing?
Marketplace: [url=http://tinyurl.com/75gc58b]Itza[/url] - Review: [url=http://tinyurl.com/ctdz422]Itza Update[/url]Hello,
1. To display the text, we need to override the ToString method for CustomerType
public class CustomerType
public int Id { get; set; }
public string Description { get; set; }
public CustomerType(int id, string description)
this.Id = id;
this.Description = description;
public override string ToString()
return this.Description.ToString();
2. To get the cell's value changed, we could pass the cell instance to that editing control and get its value changed with the following way.
public partial class CustomerTypeSearch : UserControl, IDataGridViewEditingControl
private DataGridView dataGridView;
private int rowIndex;
private bool valueChanged = false;
private CustomerTypeCell currentCell = null;
public CustomerTypeCell OwnerCell
get { return currentCell; }
set
currentCell = null;
currentCell = value;
public CustomerTypeSearch()
InitializeComponent();
private void buttonSearch_Click(object sender, EventArgs e)
Form2 f = new Form2();
DialogResult dr = f.ShowDialog(this);
if (dr == DialogResult.OK)
currentCell.Value = f.SelectedValue;
this.textBoxSearch.Text = f.SelectedValue.Description;
#region IDataGridViewEditingControl implementation
public object EditingControlFormattedValue
get
if (this.currentCell.Value != null)
return (this.currentCell.Value as CustomerType).Description;
else
return null;
set
if (this.currentCell != null)
(this.currentCell.Value as CustomerType).Description = (string)value;
public object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context)
return EditingControlFormattedValue;
public void ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle)
this.BorderStyle = BorderStyle.None;
this.Font = dataGridViewCellStyle.Font;
public int EditingControlRowIndex
get { return rowIndex; }
set { rowIndex = value; }
public bool EditingControlWantsInputKey(Keys key, bool dataGridViewWantsInputKey)
return false;
public void PrepareEditingControlForEdit(bool selectAll)
//No preparation needs to be done
public bool RepositionEditingControlOnValueChange
get { return false; }
public DataGridView EditingControlDataGridView
get { return dataGridView; }
set { dataGridView = value; }
public bool EditingControlValueChanged
get { return valueChanged; }
set { valueChanged = value; }
public Cursor EditingPanelCursor
get { return base.Cursor; }
#endregion
private void CustomerTypeSearch_Resize(object sender, EventArgs e)
buttonSearch.Left = this.Width - buttonSearch.Width;
textBoxSearch.Width = buttonSearch.Left;
Cell:
public class CustomerTypeCell : DataGridViewTextBoxCell
public CustomerTypeCell()
: base()
public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle);
CustomerTypeSearch ctl = DataGridView.EditingControl as CustomerTypeSearch;
ctl.OwnerCell = this;
public override Type EditType
get { return typeof(CustomerTypeSearch); }
public override Type ValueType
get { return typeof(CustomerType); }
public override object DefaultNewRowValue
get { return null; }
Result:
Regards,
Carl
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
Oracle.DataAccess.Client.OracleDataAdapter.Update not working
Hi
I am using the Oracle.DataAccess.Client.OracleDataAdapter from Oracle.DataAccess runtime version v4.0.30319. I set the SelectCommand and retrieve data from Oracle without any problems using the adapter to fill a datatable. I then use the DataTable.Clear method to remove all rows and fill it again from a different source using a different adapter. I use the Oracle.DataAccess.Client.OracleCommandBuilder to create the Insert and Update commands and finally I call the update command of the using the original adapter in order to update the Oracle database but nothing is updated.
I examine the table row count at each stage and also display the table using a DataGridView on a form and all appears to be fine. No exception is thrown so I am stumped.
I would be grateful for any suggestions as to what I am doing wrong.
My environment is VS2010 Express
Edited by: user1947494 on 04-Feb-2011 05:46Hi,
Pretty tough without seeing any code. I really do not believe it has anything to do with the DataAdapter. What changed the specific row/rows after the second fill?
But, as a guess, take a look at the DataTable - Rows - RowState. Run the below(or some variant) method just prior to your update.
r,
dennis
public static DataTable GetDataTableChanges_Modified(DataSet dataSet, string dataTableName)
if (dataSet.Tables[dataTableName].Rows.Count > 0)
DataTable dt = dataSet.Tables[dataTableName].Clone(); ;
int c = 0;
foreach (DataRow r in dataSet.Tables[dataTableName].Rows)
DataRowState state = r.RowState;
switch (state)
case DataRowState.Modified:
DataRow anewrow_dr = dt.NewRow();
anewrow_dr.ItemArray = r.ItemArray;
dt.Rows.Add(anewrow_dr);
c = c + 1;
break;
default:
break;
if (c > 0)
return dt;
else
return null;
else
return null;
} -
DataGridView double click event
I am new to programming but not very new. I have a form (named personal_Info) that fills some person's personal data and saves it in the database table "Personal_Information".
2nd i have another form that searches from personal_information and shows result in a grid view.
Now i want is that when search result shows in DataGridView and when i double click on any row of the shown results i want (personal_info) to open and made editing at that form and save it.
Please help me with the code.I have some assumptions, you need to make changes based on your code.
private void dgvPersonalInfo_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
// Assuming that you have a Persons Table which contains a PersonRowId
var person = db.Persons.Where(x=>x.PersonRowId == e.RowIndex).Select(x=>x).FirstOrDefault();
string name = dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString();
if(person != null)
personal_Info pForm = new personal_Info();
// Assuming you have a string name property in your personal_info form
pForm.name = name;
pForm.Show();
After showing values on the form make changes and save it with your save button which will update the values in your database. -
Hyperlink back to a datagridview
Hi. I am using cr. 10.5 and visual studio 2008. I have a crystal report that was written in the application. I would like to have the user be able to click on a ID (that is on the detail line) and open a datagridview with that record on it. Then the user could update the notes area on the record. I've been trying to set up a hyperlink in the cr report on the ID field, but I can't seen to get the syntax correct to link it. I would appreciate any available help. I've about exhausted all my other tek sites to find an example of what I want to do.
Thanks
CathyWhy not use a formula to construct a hyperlink to take you to your datagrid action page? You could use a formula like this to grab the primary key of your database table.
stringVar hyperlink := "http://mysite.com/datagrid.aspx?id=";
hyperlink := hyperlink + ToText({Customer.Customer ID}, 0); -
Changes commited to the database only after I update OracledataAdapter twice
Hi. I am using oracledataadapter to manage the data which is eventually displayed in winform datagridview (Visual Studio 2012)
everything works fine , but I have to click "Save" buttin twice to see the changes in the database (Oracle express 11g)
Can you please advice....
Here is my code
it is very simple
1. Obtain connection
2. Create dataadapter
3. Create commands
4. Fill the datatable and dataset
public partial class Concordance : Form
OracleDataAdapter setupAdapter;
DataSet projDataset;
OracleConnection conn;
//binding sources
BindingSource setupBindingSource = new BindingSource();
DataTable setupTable;
public Concordance()
InitializeComponent();
//load tables
loadSetup();
//setup table
private void loadSetup()
string oradb = ConfigurationManager.ConnectionStrings["OpenU"].ConnectionString;
conn = new OracleConnection(oradb);
try
// using (conn = new OracleConnection(oradb))
setupAdapter = new OracleDataAdapter("select * from ou_setup", conn);
OracleCommandBuilder builder = new OracleCommandBuilder(setupAdapter);
projDataset = new DataSet("Concordia");
setupTable = new DataTable("Setup");
projDataset.Tables.Add(setupTable);
setupAdapter.Fill(projDataset,"Setup");
//bind the gataGridView
this.setupGrid.DataSource = projDataset.Tables["Setup"];
this.setupBindingSource.DataSource = projDataset.Tables["Setup"];
this.setupNavigator.BindingSource = this.setupBindingSource;
catch (Exception ex)
string error = ex.Message;
MessageBox.Show(error);
private void saveSetupBtn_Click(object sender, EventArgs e)
// only after sabe button clicked for the second time the changes are commited into the database
this.setupAdapter.Update(projDataset.Tables["Setup"]);
MessageBox.Show("saved");How are you reading in the object initially? The problem is likely that you are modifying an object from the session cache. When you then read in the object from the uow, it uses the object in the session cache as the back up. So there will not appear to be any changes to persist to the database.
You will need to make a copy of the object for modification, or use the copy from the unitofwork to make the changes instead of working directly on the object in the session. Disabling the cache means there is no copy in the session cache to use as a back up, so the uow read has to build an object from the database.
Best Regards,
Chris -
Datagridview to database access
hi, I need help whenever I run my project there's a message saying "cannot find column 5" thanks!
form 1
contains:
datagridview(dgv1) linked to database access
btnNew- allows me to add data in my datagridview
btnEdit- allows me to edit data in my datagridview
btnDelete - to delete
syntax:
Imports System.Data.OleDb
Public Class frmMain
Public rows As Integer
Public key As String
Public num As Integer
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
conn()
loading()
End Sub
Public Sub loading()
com = New OleDbCommand("SELECT * FROM Products", con)
da = New OleDbDataAdapter(com)
ds = New DataSet()
da.Fill(ds, "Employees")
For num = 0 To ds.Tables("Employees").Rows.Count - 1
dgv1.Rows.Add(ds.Tables("Employees").Rows(num).Item(0).ToString, ds.Tables("Employees").Rows(key).Item(1).ToString, ds.Tables("Employees").Rows(key).Item(2).ToString, ds.Tables("Employees").Rows(key).Item(3).ToString,
ds.Tables("Employees").Rows(key).Item(4).ToString, ds.Tables("Employees").Rows(key).Item(5).ToString, ds.Tables("Employees").Rows(key).Item(6).ToString)
Next
dgv1.Sort(dgv1.Columns(0), System.ComponentModel.ListSortDirection.Ascending)
End Sub
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
Form2.txtID.Text = dgv1.Rows(rows).Cells(0).Value
Form2.txtLast.Text = dgv1.Rows(rows).Cells(1).Value
Form2.txtFirst.Text = dgv1.Rows(rows).Cells(2).Value
Form2.txtTitle.Text = dgv1.Rows(rows).Cells(3).Value
Form2.txtCourt.Text = dgv1.Rows(rows).Cells(4).Value
Form2.txtUsername.Text = dgv1.Rows(rows).Cells(5).Value
Form2.txtPassword.Text = dgv1.Rows(rows).Cells(6).Value
key = "Edit"
Form2.btnSave.Text = "Update Changes"
Form2.Show()
Me.Hide()
End Sub
Private Sub dgv1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgv1.CellContentClick
rows = dgv1.CurrentRow.Index
End Sub
Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
If MsgBox("Are you sure?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
com = New OleDbCommand("DELETE * FROM Products WHERE ProductID = '" & dgv1.CurrentRow.Cells(0).Value.ToString & "'", con)
con.Open()
com.ExecuteNonQuery()
con.Close()
dgv1.Rows.Clear()
loading()
MsgBox("Okay")
End If
End Sub
Private Sub btnNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNew.Click
key = "Add"
Form2.btnSave.Text = "Add Item"
Form2.Show()
Me.Hide()
End Sub
End Class
FORM 2
contains
txtID
txtLast
txtFirst
txtTitle
txtCourt
txtUsername
txtPassword
btnSave - allows me to save changes from editing my data and adding data
synatx:
Imports System.Data.OleDb
Public Class Form2
Dim final As Boolean
Private Sub Form2_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
frmMain.Show()
End Sub
Private Sub Form2_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If final = True Then
e.Cancel = True
Else
Dim res As MsgBoxResult = MsgBox("This will IGNORE CHANGES... Are you sure?", MsgBoxStyle.YesNo)
If res = MsgBoxResult.No Then
e.Cancel = True
End If
End If
End Sub
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Select Case frmMain.key
Case "Edit"
com = New OleDbCommand("UPDATE Products SET EmployeeID = '" & txtID.Text & "', LastName = '" & txtLast.Text & "', FirstName = '" & txtFirst.Text &
"', Title = '" & txtTitle.Text & "', TitleOfCourtesy = '" & txtCourt.Text & "', Username = '" & txtUsername.Text & "', Password = '" & txtPassword.Text & "' WHERE EmployeeID = '"
& txtID.Text & "'", con)
con.Open()
com.ExecuteNonQuery()
MsgBox("OK")
con.Close()
frmMain.dgv1.Rows.Clear()
frmMain.loading()
final = True
Me.Close()
Case "Add"
con.Open()
com = New OleDbCommand("INSERT INTO Employees(EmployeeID, LastName, FirstName, Title, TitleOfCourtesy, Username, Password) VALUES(@Column1, @Column2, @Column3, @Column4, @Column5, @Column6, @column7)",
con)
com.Parameters.Add(New OleDbParameter("@Column1", txtID.Text))
com.Parameters.Add(New OleDbParameter("@Column2", txtLast.Text))
com.Parameters.Add(New OleDbParameter("@Column3", txtFirst.Text))
com.Parameters.Add(New OleDbParameter("@Column4", txtTitle.Text))
com.Parameters.Add(New OleDbParameter("@Column5", txtCourt.Text))
com.Parameters.Add(New OleDbParameter("@Column6", txtUsername.Text))
com.Parameters.Add(New OleDbParameter("@Column7", txtPassword.Text))
com.ExecuteNonQuery()
con.Close()
MsgBox("Okay")
frmMain.dgv1.Rows.Clear()
frmMain.loading()
final = True
Me.Close()
End Select
End Sub
End Class
MODULE1- contains my other variables
Imports System.Data.OleDb
Module Module1
Public con As OleDbConnection
Public com As OleDbCommand
Public cb As OleDbCommandBuilder
Public da As OleDbDataAdapter
Public ds As DataSet
Public sql As String
Public EmployeeID As Integer
Public Sub Conn()
con = New OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= D:\nica\IT.mdb"
End Sub
End ModuleDani,
There is a lot wrong in your code.
However, first start with creating a new project.
In that you can copy parts of your code and then first. Remove that module, it is vintage try OOP programming.
Secondly, use one form, or use dialog (modal) forms (which are shown with showndialog.
There is so much missunderstood by you in your code, that trying to help you would only end that it would even be worse when you start to copy that in your original code.
Here on our website a sample how to do that.
You probably don't need much more code than that.
http://www.vb-tips.com/CommandBuilderDataGridview.ASPX
Success
Cor -
Edit/update function not working properly on visual basic 2012
help, i'm working on a update function on my aplication program using visual studio ultimate 2012 VB.
after i fixed the error on my coding, i debug the program with f5. but, when i tried to update the data on the datagridview it doesn't change even thought the messagebox "data has been updated" show up.
how do i fix this problem?
here is the coding for update function:
form1:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ClassSiswa.ubahdata(New SqlConnection, (txt_nis.Text), (txt_nisn.Text), (txt_namasiswa.Text), (cmb_kelaminsiswa.Text), (txt_kotalahir.Text), (DTP_siswa.Text), (cmb_agamasiswa.Text), (txt_beratsiswa.Text), (txt_tinggi_badan.Text))
datagridview()
End Sub
Private Sub UpdateDataSiswa()
ClassSiswa.Nis = txt_nis.Text
ClassSiswa.Nisn = txt_nisn.Text
ClassSiswa.Nama_Siswa = txt_namasiswa.Text
ClassSiswa.Tanggal_Lahir = DTP_siswa.Text
ClassSiswa.Jenis_Kelamin = cmb_kelaminsiswa.Text
ClassSiswa.Kota_Lahir = txt_kotalahir.Text
ClassSiswa.Agama = cmb_agamasiswa.Text
ClassSiswa.Tinggi_Badan = txt_tinggi_badan.Text
ClassSiswa.Berat_Badan = txt_beratsiswa.Text
ClassSiswa.Updatesiswa(ClassSiswa.opencon, (txt_nis.Text))
datagridview()
End Sub
classSiswa:
Public Shared Sub ubahdata(ByVal _cn As SqlClient.SqlConnection, ByVal _Nis As String, ByVal _Nisn As String, ByVal _nama_siswa As String, ByVal _jenis_kelamin As String, ByVal _kota_lahir As String, ByVal _tanggal_lahir As String, ByVal _agama As String, ByVal _berat_badan As String, ByVal tinggi_badan As String)
Dim sql As New SqlClient.SqlCommand
sql.Connection = _cn
sql.CommandType = CommandType.Text
sql.CommandText = "update siswa set nis='" & Nis & "',nisn='" & Nisn & "',nama_siswa='" & Nama_Siswa & "',jenis_kelamin='" & Jenis_Kelamin & "' ,kota_lahir='" & Kota_Lahir & "',tanggal_lahir='" & Tanggal_Lahir & "'agama='" & Agama & "'berat_badan='" & Berat_Badan & "',tinggi_badan='" & tinggi_badan & "'"
MessageBox.Show(" Data Telah Diupdate")
ClassSiswa.closecon()
End Sub
Public Shared Sub Updatesiswa(ByVal _Cn As SqlClient.SqlConnection, ByVal _nis As String)
Dim sql As SqlClient.SqlCommand
sql = New SqlClient.SqlCommand
sql.Connection = _Cn
sql.CommandType = CommandType.Text
sql.CommandText = "Update siswa Set nis = '" & Nis & "', nisn = '" & Nisn & "' where nis = '" & _nis & "'"
sql.ExecuteNonQuery()
End SubHello,
A DataGridView knows nothing about the updates done as shown above, you need to update any rows that have changed yourself. For example. lets say I loaded data from a database table into a DataTable, create a BindingSource and assign that DataTable as the
DataSource for the BindingSource. The BindingSource becomes the DataSource of the DataGridView so now when you moved up/down rows in the DataGridView you are changing position in the BindingSource and can read this data via BindingSource.Current by casting
Current to a DataRowView then access the Row property with Field(Of T or SetField(Of T. Couple this will logic to locate rows that may not be the current row and we still can use SetField(Of T)(Col,Value) to update data in the BindingSource which is then immediately
reflected in the DataGridView.
The following is for MS-Access but the same logic applies for SQL-Server database via SqlClient data provider rather than
OleDb data provider.
Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my webpage under my profile
but do not reply to forum questions. -
Save data from unbound datagridview to database table.
Hi, i have a unbound datagridview that contain 8 columns i added data in it using the following code:
Dim i As Integer = DataGridViewX1.Rows.Count - 1
Me.DataGridViewX1.Rows.Add()
With Me.DataGridViewX1.Rows(i)
.Cells("id").Value = Format(i, "0000")
.Cells("design").Value = TextBoxX1.Text
.Cells("than").Value = TextBoxX2.Text
.Cells("lace").Value = TextBoxX3.Text
.Cells("color").Value = ComboBoxEx1.Text
.Cells("barcode").Value = ComboBoxEx1.Text
.Cells("received").Value = TextBoxX4.Text
.Cells("description").Value = TextBoxX5.Text
End With
when i click on the add button the data is added to the datagridview. Now what i want is to save this data that i added in unbounded datagridview to my database table.
Plz Help Me...
Thank You.From DataGridView to a MS Access?
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports System.Windows.Forms
Public Class Form1
Inherits System.Windows.Forms.Form
Private bindingSource1 As New BindingSource()
Private dataAdapter As New OleDbDataAdapter()
<STAThreadAttribute()> _
Public Shared Sub Main()
Application.Run(New Form1())
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Ryan\Desktop\Coding\Microsoft Access\Northwind_2012.mdb"
Dim selectCommand As String
Dim connection As New OleDbConnection(connectionString)
selectCommand = "Select * From MyExcelTable ORDER BY ID"
Me.dataAdapter = New OleDbDataAdapter(selectCommand, connection)
With DataGridView1
.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
End With
Dim commandBuilder As New OleDbCommandBuilder(Me.dataAdapter)
Dim table As New DataTable()
table.Locale = System.Globalization.CultureInfo.InvariantCulture
Me.dataAdapter.Fill(table)
Me.bindingSource1.DataSource = table
Dim data As New DataSet()
data.Locale = System.Globalization.CultureInfo.InvariantCulture
DataGridView1.DataSource = Me.bindingSource1
Me.DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Aqua
Me.DataGridView1.AutoResizeColumns( _
DataGridViewAutoSizeColumnsMode.AllCells)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, btnUpdate.Click
Dim table As New DataTable()
Me.bindingSource1 = Me.DataGridView1.DataSource
table = Me.bindingSource1.DataSource
Me.dataAdapter.Update(table)
End Sub
End Class
Knowledge is the only thing that I can give you, and still retain, and we are both better off for it.
Maybe you are looking for
-
Pages 5.0--I can't open more than one document at a time.
Pages 5--I can't open more than 1 document/file. I can look up files in iCloud/computer, click to open, but the file never opens in Pages 5. I have to quit Pages, reopen to get another document (but still cannot open more than that first doc). I s
-
How to Enable IPv6 Connection Permanently ?
How to Enable IPv6 Connection Permanently ? I've searched Microsoft's websites for hours trying to enable IPv6 but no one seems to know. I've enabled IPv6 from the registry but it disables after restart. I think ESET Endpoint is disabling it. I have
-
After upgrading to SL I have white background in TM
Why is this, everything else is fine and working perfectly.
-
Whats the difference between Authentication and Login check up ?
whats the difference between Authentication and Login check up ?
-
When does select for update release locks
Hello all, Does anyone know when Oracle realeases the row locks when a select for update is issued? Does Oracle realase the row lock at the time when an actual update statement is issued for the locked row, or does it wait until a commit statment is