943,809 Members | Top Members by Rank

Ad:
  • C# Discussion Thread
  • Unsolved
  • Views: 4010
  • C# RSS
Sep 6th, 2008
0

Updating SQL database, Please help

Expand Post »
Can someone please help with the following problem I am trying to update a sql database through a command builder but I keep getting an sql exception (Additional information: System error.). I dont know where I am going wrong because I thought the command builder should carry out the update automatically.

the table on the sql database is called 'MovieTable1' and the dataset is called 'MovSet1'. please see the code I am using below....any help would be appreciated because this is now giving me a headache.



C# Syntax (Toggle Plain Text)
  1. using System;
  2. using System.Drawing;
  3. using System.Collections;
  4. using System.ComponentModel;
  5. using System.Windows.Forms;
  6. using System.Data;
  7. using System.Data.Common;
  8. using System.Data.SqlClient;
  9.  
  10. namespace MovieDiary
  11. {
  12. /// <summary>
  13. /// Summary description for Form1.
  14. /// </summary>
  15. public class Form1 : System.Windows.Forms.Form
  16. {
  17. private System.Windows.Forms.DataGrid dataGrid1;
  18. private System.Windows.Forms.Button button1;
  19. /// <summary>
  20. /// Required designer variable.
  21. /// </summary>
  22. private System.ComponentModel.Container components = null;
  23.  
  24. public static SqlConnection Mcon = new SqlConnection("Server=SHERMAN2;Database =MDatabase; data source=\"SH" +
  25. "ERMAN2\\SQLEXPRESS\"");
  26.  
  27.  
  28. public static SqlDataAdapter MovAdapt = new SqlDataAdapter("SELECT * FROM MovTable1", Mcon);
  29. SqlCommandBuilder cb = new SqlCommandBuilder(MovAdapt);
  30. DataTableMapping myNewMapping =
  31. new DataTableMapping("MovMap","MovTable1");
  32. public static DataSet Movset1 = new DataSet();
  33.  
  34. public Form1()
  35. {
  36. //
  37. // Required for Windows Form Designer support
  38. //
  39. InitializeComponent();
  40.  
  41. //
  42. // TODO: Add any constructor code after InitializeComponent call
  43. //
  44. }
  45.  
  46. /// <summary>
  47. /// Clean up any resources being used.
  48. /// </summary>
  49. protected override void Dispose( bool disposing )
  50. {
  51. if( disposing )
  52. {
  53. if (components != null)
  54. {
  55. components.Dispose();
  56. }
  57. }
  58. base.Dispose( disposing );
  59. }
  60.  
  61. #region Windows Form Designer generated code
  62. /// <summary>
  63. /// Required method for Designer support - do not modify
  64. /// the contents of this method with the code editor.
  65. /// </summary>
  66. private void InitializeComponent()
  67. {
  68. this.dataGrid1 = new System.Windows.Forms.DataGrid();
  69. this.button1 = new System.Windows.Forms.Button();
  70. ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
  71. this.SuspendLayout();
  72. //
  73. // dataGrid1
  74. //
  75. this.dataGrid1.DataMember = "";
  76. this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
  77. this.dataGrid1.Location = new System.Drawing.Point(0, 0);
  78. this.dataGrid1.Name = "dataGrid1";
  79. this.dataGrid1.Size = new System.Drawing.Size(448, 128);
  80. this.dataGrid1.TabIndex = 0;
  81. //
  82. // button1
  83. //
  84. this.button1.Location = new System.Drawing.Point(104, 168);
  85. this.button1.Name = "button1";
  86. this.button1.Size = new System.Drawing.Size(128, 23);
  87. this.button1.TabIndex = 1;
  88. this.button1.Text = "Update And Save";
  89. this.button1.Click += new System.EventHandler(this.button1_Click);
  90. //
  91. // Form1
  92. //
  93. this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
  94. this.ClientSize = new System.Drawing.Size(472, 266);
  95. this.Controls.Add(this.button1);
  96. this.Controls.Add(this.dataGrid1);
  97. this.Name = "Form1";
  98. this.Text = "Form1";
  99. this.Load += new System.EventHandler(this.Form1_Load);
  100. ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
  101. this.ResumeLayout(false);
  102.  
  103. }
  104. #endregion
  105.  
  106. /// <summary>
  107. /// The main entry point for the application.
  108. /// </summary>
  109. [STAThread]
  110. static void Main()
  111. {
  112. Application.Run(new Form1());
  113. }
  114.  
  115. public void Form1_Load(object sender, System.EventArgs e)
  116. {
  117.  
  118. MovAdapt.Fill(Movset1,"MovTable1");
  119. dataGrid1.DataSource = Movset1;
  120. Show();
  121.  
  122.  
  123. }
  124.  
  125. public void button1_Click(object sender, System.EventArgs e)
  126. {
  127.  
  128.  
  129. MovAdapt.Update(Movset1, "MovTable1");
  130. Movset1.AcceptChanges();
  131.  
  132.  
  133. }
  134. }
  135. }
Last edited by cscgal; Sep 6th, 2008 at 2:35 pm. Reason: Added code tags
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
markyjj is offline Offline
6 posts
since Sep 2008
Sep 6th, 2008
0

Re: Updating SQL database, Please help

Whats the actual error you get? (And do you have read/write permissions on the database)
Reputation Points: 196
Solved Threads: 190
Posting Virtuoso
LizR is offline Offline
1,735 posts
since Aug 2008
Sep 6th, 2008
0

Re: Updating SQL database, Please help

Click to Expand / Collapse  Quote originally posted by LizR ...
Whats the actual error you get? (And do you have read/write permissions on the database)

Well when I press the update button which has the update method I then get the following exception:

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in system.data.dll

Additional information: System error.


How do I check if I have read/write permissions on the database?, because I assumed I have since I can read the data when I use the fill method.

thanks
Reputation Points: 10
Solved Threads: 0
Newbie Poster
markyjj is offline Offline
6 posts
since Sep 2008
Sep 7th, 2008
0

Re: Updating SQL database, Please help

Looks like you're not generating the update command. It isn't actually created until you call SqlCommandBuilder.GetUpdateCommand(). You'll need something like this:

C# Syntax (Toggle Plain Text)
  1. MovAdapt.UpdateCommand = cb.GetUpdateCommand

This article has a good explanation of how it works.
Reputation Points: 182
Solved Threads: 71
Posting Pro in Training
gusano79 is offline Offline
475 posts
since May 2004
Sep 8th, 2008
0

Re: Updating SQL database, Please help

Click to Expand / Collapse  Quote originally posted by gusano79 ...
Looks like you're not generating the update command. It isn't actually created until you call SqlCommandBuilder.GetUpdateCommand(). You'll need something like this:

C# Syntax (Toggle Plain Text)
  1. MovAdapt.UpdateCommand = cb.GetUpdateCommand

This article has a good explanation of how it works.
I have tried using the following code: MovAdapt.UpdateCommand = cb.GetUpdateCommand but now I get the following exception:

An unhandled exception of type 'System.InvalidOperationException' occurred in system.data.dll

Additional information: Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.


Thanks for any further help.
Reputation Points: 10
Solved Threads: 0
Newbie Poster
markyjj is offline Offline
6 posts
since Sep 2008
Sep 9th, 2008
0

Re: Updating SQL database, Please help

hmp
Reputation Points: 10
Solved Threads: 0
Newbie Poster
nevoj is offline Offline
3 posts
since Jul 2008
Sep 10th, 2008
0

Re: Updating SQL database, Please help

Click to Expand / Collapse  Quote originally posted by markyjj ...
An unhandled exception of type 'System.InvalidOperationException' occurred in system.data.dll

Additional information: Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.
Ah, yes. The command builder also requires that your SELECT statement return a primary key or unique index.

If your table has either of those, you may be able to get away with simply adding the appropriate column(s) to the SELECT statement.

If not, you'll have to write the update command yourself. Here's what it might look like:

C# Syntax (Toggle Plain Text)
  1. using(SqlConnection connection = new SqlConnection("<connection string>"))
  2. {
  3. SqlDataAdapter adapter = new SqlDataAdapter(
  4. "SELECT SomeField, SomeOtherField FROM Table"
  5. );
  6.  
  7. adapter.UpdateCommand = new SqlCommand(
  8. "UPDATE Table SET SomeField = @SomeField WHERE TheKey = @TheKey"
  9. );
  10.  
  11. adapter.UpdateCommand.Parameters.Add(
  12. "@TheKey", SqlDbType.Int).SourceColumn = "TheKey";
  13.  
  14. adapter.UpdateCommand.Parameters.Add(
  15. "@SomeField", SqlDbType.Binary).SourceColumn = "SomeField";
  16.  
  17. DataTable table = new DataTable();
  18.  
  19. connection.Open();
  20.  
  21. adapter.Fill(table);
  22.  
  23. foreach(DataRow row in table.Rows)
  24. {
  25. row["SomeField"] = (int)row["SomeOtherField"] == 42;
  26. }
  27.  
  28. adapter.Update(table);
  29. }
Reputation Points: 182
Solved Threads: 71
Posting Pro in Training
gusano79 is offline Offline
475 posts
since May 2004
Sep 10th, 2008
0

Re: Updating SQL database, Please help

Thanks again but couldnt I just enter dynamic data direct through the datagrid and then just update the table(In other words actually click on the datagrid and then type data in the list and then click on update). The added data will be movie titles, director etc so that I could just add to the list when I want to update.

regards
Reputation Points: 10
Solved Threads: 0
Newbie Poster
markyjj is offline Offline
6 posts
since Sep 2008
Sep 10th, 2008
0

Re: Updating SQL database, Please help

Click to Expand / Collapse  Quote originally posted by markyjj ...
couldnt I just enter dynamic data direct through the datagrid and then just update the table(In other words actually click on the datagrid and then type data in the list and then click on update). The added data will be movie titles, director etc so that I could just add to the list when I want to update.
Short answer is no. How will your application know what SQL to send to your database to insert, update, or delete records?

I wish I had a better answer for you, but this is how it works. There are other ways to do what you want within ADO.NET, but they require more code and more manual management of the database. I believe that what I'm describing here is one of the simpler methods, and I think the most decoupled from the database itself.

Longer answer: DataGrid is there to provide a user interface. It can display and manage data based on a variety of underlying data-holding classes. We're looking at a DataSet or DataTable as the backing object for your DataGrid . Both of these are in-memory representations, i.e., they are a copy of your data, and they don't represent a direct connection to the database. SqlDataAdapter is probably the easiest way manage the link between these data objects and your database. At a minimum, you need to write the SELECT statement, and if you aren't able to use SqlCommandBuilder you'll also need to write appropriate INSERT , UPDATE , and DELETE statements for full database operation. Once that's done, though, the adapter's Update method takes care of all of the details.

If the .NET Framework 3.5 is available to you, there is also LINQ. It provides a language-integrated query facility that is much more intuitive than ADO.NET mechanisms and takes considerably fewer lines of code to do the same things. Using LINQ, however, is a whole different discussion--I only mention it in case you aren't familiar with it.
Reputation Points: 182
Solved Threads: 71
Posting Pro in Training
gusano79 is offline Offline
475 posts
since May 2004
Jul 21st, 2010
0
Re: Updating SQL database, Please help
hi.
I'm using this code:

using(SqlConnection connection = new SqlConnection("<connection string>"))
{
SqlDataAdapter adapter = new SqlDataAdapter(
"SELECT SomeField, SomeOtherField FROM Table"
);

adapter.UpdateCommand = new SqlCommand(
"UPDATE Table SET SomeField = @SomeField WHERE TheKey = @TheKey"
);

adapter.UpdateCommand.Parameters.Add(
"@TheKey", SqlDbType.Int).SourceColumn = "TheKey";

adapter.UpdateCommand.Parameters.Add(
"@SomeField", SqlDbType.Binary).SourceColumn = "SomeField";

DataTable table = new DataTable();

connection.Open();

adapter.Fill(table);

foreach(DataRow row in table.Rows)
{
row["SomeField"] = (int)row["SomeOtherField"] == 42;
}

adapter.Update(table);
}
but I have an error in "adapter.Update(table);"
the error is:
the update requires UpdateCommand has a connection object. UpdateCommand property of the connection has not been initialized.

I need your help.
please...
Last edited by Renas22; Jul 21st, 2010 at 1:58 pm.
Reputation Points: 10
Solved Threads: 0
Newbie Poster
Renas22 is offline Offline
1 posts
since Jul 2010

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C# Forum Timeline: Close Login Form
Next Thread in C# Forum Timeline: how to use registry to check if a file matches the one on server





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC