473,725 Members | 2,180 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem in Saving in ADO.Net

108 New Member
Hi guys,

I would like to ask your help about saving in ado.net. I was able to update it only on the display but when I check the database, it is not updated. I paste below my code and hopefully you can help me.

Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Data;
  5. using System.Data.SqlClient;
  6.  
  7. namespace ADOTest5
  8. {
  9.     class Connect
  10.     {
  11.         //declare member var
  12.         private SqlConnection _con;
  13.         private SqlDataAdapter _da;
  14.         private DataSet _ds;
  15.         private DataTable _dt;
  16.         private string con_string;
  17.         private string com_string;
  18.         //private System.Windows.Forms.ListBox listBox;
  19.  
  20.         public Connect()
  21.         {
  22.             con_string = global::ADOTest5.Properties.Settings.Default.MyDatabaseConnectionString;
  23.             com_string = "SELECT * FROM dbo.Customers";
  24.  
  25.             //this.listBox = new System.Windows.Forms.ListBox();
  26.         }
  27.  
  28.         public bool GetConnected()
  29.         {
  30.             try
  31.             {
  32.                 _con = new SqlConnection(con_string);
  33.                 _da = new SqlDataAdapter(com_string, con_string);
  34.                 _con.Open();
  35.  
  36.                 //populate dataset
  37.                 //_ds = new DataSet();
  38.                 //_da.Fill(_ds, "Customers");
  39.  
  40.                 InitializeCommands();
  41.             }
  42.             catch(Exception ex)
  43.             {
  44.                 Console.WriteLine("Connection Error" + ex.Message);
  45.                 _con = null;
  46.                 return false;
  47.             }
  48.  
  49.             return true;
  50.         }
  51.  
  52.         public void GetClosed()
  53.         {
  54.             if (_con != null)
  55.             {
  56.                 _con.Close();
  57.                 _con = null;
  58.             }
  59.         }
  60.  
  61.         //fill the listbox
  62.         public void PopulateListBox(Object obj)
  63.         {
  64.             //populate dataset
  65.             _ds = new DataSet();
  66.             _da.Fill(_ds, "Customers");
  67.  
  68.             System.Windows.Forms.ListBox listBox =
  69.                 (System.Windows.Forms.ListBox)obj;
  70.  
  71.             listBox.Items.Clear();
  72.             _dt = _ds.Tables["Customers"];
  73.  
  74.             //Loop through the DataSet and add each row 
  75.             // to the listbox
  76.             foreach (DataRow drow in _dt.Rows)
  77.             {
  78.                 listBox.Items.Add(drow["Id"] + ", " + drow["Lname"] + ", " + drow["Fname"]);
  79.             }
  80.  
  81.             //Prepare Commands
  82.             //InitializeCommands();
  83.         }
  84.  
  85.         //Bind parameters to each column;params means variable # of param
  86.         public void AddParams(SqlCommand cmd, params string[] cols)
  87.         {
  88.             //add each parameter
  89.             cmd.Parameters.Add("@Id", SqlDbType.Int, 0, "Id");
  90.             cmd.Parameters.Add("@Fname", SqlDbType.NVarChar, 9, "Fname");
  91.             cmd.Parameters.Add("@Lname", SqlDbType.NVarChar, 9, "Lname");
  92.             //foreach (String column in cols)
  93.             //{
  94.             //    cmd.Parameters.Add("@", SqlDbType.NVarChar, 0, column);
  95.             //}
  96.         }
  97.  
  98.         public void InitializeCommands()
  99.         {
  100.             //prepare UpdateCommand
  101.             _da.UpdateCommand = _con.CreateCommand();
  102.             _da.UpdateCommand.CommandText =
  103.                 "UPDATE [dbo].[Customers] SET [Fname] = @Fname, [Lname] = @Lname" +
  104.                 " WHERE ([Id] = @Id)";
  105.             AddParams(_da.UpdateCommand, "Fname", "Lname");
  106.         }
  107.  
  108.  
  109.         // Fill the firsname/lastname textbox
  110.         public void FillInfo(Object obj1, Object obj2, int index)
  111.         {
  112.             // cast to textbox; for fname
  113.             System.Windows.Forms.TextBox Tbox1 = 
  114.                 (System.Windows.Forms.TextBox) obj1;
  115.  
  116.             //for last name
  117.             System.Windows.Forms.TextBox Tbox2 =
  118.                 (System.Windows.Forms.TextBox)obj2;
  119.  
  120.             Tbox1.Text = _dt.Rows[index]["Fname"].ToString();
  121.             Tbox2.Text = _dt.Rows[index]["Lname"].ToString();
  122.         }
  123.  
  124.         public void SaveChanges(Object obj1, Object obj2, int index)
  125.         {
  126.             // cast to textbox; for fname
  127.             System.Windows.Forms.TextBox Tbox1 = 
  128.                 (System.Windows.Forms.TextBox) obj1;
  129.  
  130.             //for last name
  131.             System.Windows.Forms.TextBox Tbox2 =
  132.                 (System.Windows.Forms.TextBox)obj2;
  133.  
  134.             DataRow row = _dt.Rows[index];
  135.             row.BeginEdit();
  136.             row["Fname"] = Tbox1.Text;
  137.             row["Lname"] = Tbox2.Text;
  138.             row.EndEdit();
  139.  
  140.             _da.Update(_ds, "Customers");
  141.             _ds.AcceptChanges();
  142.         }
  143.     }
  144. }
  145.  
  146.  
  147.  
  148. using System;
  149. using System.Collections.Generic;
  150. using System.ComponentModel;
  151. using System.Data;
  152. using System.Drawing;
  153. using System.Text;
  154. using System.Windows.Forms;
  155.  
  156. namespace ADOTest5
  157. {
  158.     public partial class Form1 : Form
  159.     {
  160.         Connect c;
  161.         int index = 0;
  162.  
  163.         public Form1()
  164.         {
  165.             InitializeComponent();
  166.             c = new Connect();
  167.         }
  168.  
  169.         private void LoadButton_Click(object sender, EventArgs e)
  170.         {
  171.             //Connect c = new Connect();
  172.             if (c.GetConnected())
  173.             {
  174.                 c.PopulateListBox(this.listBox1);
  175.                 c.GetClosed();
  176.             }
  177.         }
  178.  
  179.         private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
  180.         {
  181.             //display the index of selected items
  182.             //this.FirstNameTbox.Text = this.listBox1.SelectedIndex.ToString();
  183.             //int index = this.listBox1.SelectedIndex;
  184.             index = this.listBox1.SelectedIndex;
  185.             c.FillInfo(this.FirstNameTbox, this.LastNameTbox, index);
  186.         }
  187.  
  188.         private void SaveButton_Click(object sender, EventArgs e)
  189.         {
  190.             if (c.GetConnected())
  191.             {
  192.                 c.SaveChanges(this.FirstNameTbox, this.LastNameTbox, index);
  193.                 c.PopulateListBox(this.listBox1);
  194.             }
  195.             c.GetClosed();
  196.             //c.SaveChanges(this.FirstNameTbox, this.LastNameTbox, index);
  197.             //c.PopulateListBox(this.listBox1);
  198.         }
  199.     }
  200. }
Feb 8 '08 #1
1 1337
kenobewan
4,871 Recognized Expert Specialist
I believe that your update command is not called, seems like you are calling InitializeComma nds in the wrong place. HTH.
Feb 8 '08 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

12
18694
by: annoyedtuna | last post by:
I'm having nightmares with CSS at the moment. Can anyone help me out? I'm including my stylesheet using the following code <head> <title>My Title.</title> <link rel="stylesheet" href="stylesheet.css" type="text/css"></link> </head> In IE this works fine
13
9534
by: Bob Darlington | last post by:
I have a repair and backup database routine which runs when a user closes down my application. It works fine in my development machine, but breaks on a client's at the following line: If Dir(strLDB) <> "" Then Kill (strLDB) where strLDB is the path to the ldb file. The client advises that the ldb doesn't lurk after the program closes. Any ideas?
1
5237
by: mimmo | last post by:
I have a problem while calculating timezone (from Europe/Rome to Brazil/East). Can someone help me ?? Thank you, Mimmo. On this site http://www.timezoneconverter.com/cgi-bin/tzc.tzc I have for this date 2003/01/01 00:00:00:
3
5468
by: Kidus Yared | last post by:
I am having a problem displaying Unicode characters on my Forms labels and buttons. After coding Button1.Text = unicode; where the unicode is a Unicode character or string (‘\u1234’ or “\u1234”) It seems to work the first time I set the button to the Unicode character. After a while, when saving my code, I get a pop-up window stating that I need to save the file as a Unicode else my changes will not be saved. Seance I do not want...
5
7504
by: Karl | last post by:
Hi, I have some code that will save the contents of a Rich Text Box in either a Text or Rich Text Format file. The code is using the SaveFileDialog and is working correctly. I have been testing the code and added in some exception handling to cater for any problems. During testing I have found that if I attempt to save to a floppy disc that is full, a System.IO.IOException is raied with the message "There is not enough space on the...
5
2733
by: IkBenHet | last post by:
Hello, I use this script to upload image files to a folder on a IIS6 server: ******************* START UPLOAD.ASPX FILE ********************** <%@ Page Language="VB" Debug="true" %>
7
2308
by: Nathan Sokalski | last post by:
I am having a problem saving an image with the same name it originally had. I have two similar versions of my code, one in which I close the FileStream used to open the original image before saving, the other in which I close the FileStream afterwards, although both return the same error. Here are the two versions of the code and the errors they each return (NOTE: I rebooted immediately before running each of these versions so that I knew they...
0
1438
by: Waqas.L.Khan | last post by:
Hi guys, I have a problem when trying to create an image file. Basically my code takes any file and gets it's system icon using SHGetFileInfo and then saves the file either by converting it into a bmp and saving to disk or by saving the icon using a filestream. In both cases saving the file works fine. However, when I open the newly created file from explorer I notice something peculiar. The file has a black background. I would have...
6
3073
by: BobLewiston | last post by:
When I try to save a new (inserted) record in an SQL database, I get the following System.Runtime.InteropServices.ExternalException message: I have to either find out how to insert an appropriate value into the PasswordHash column OR make SQL Server Management Studio allow NULL in the PasswordHash column. I discovered I could do the latter in SQL Server Management Studio via: expand table | expand Columns | right-click PasswordHash...
2
3879
by: BobLewiston | last post by:
Some of you may have seen my earlier thread PasswordHash NULL problem. Ive started a new thread because investigation has shown that the problem is actually quite different than I previously stated. Also please note that this is unrelated to another of my previous threads, dataAdapter.Update problem, which incidentally has been resolved. Im learning SQL. Im accessing database SQL2008 AdventureWorks, table Person.Contact, which has a...
0
8888
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
8752
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9257
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9176
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9113
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8097
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4519
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2635
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.