I have already connect my SQL database in C# windows application, Now, can somebody please give me sample codes for data manipulation, add/edit/delete of records....THANK you!

Dani AI

Generated

The thread shows a working read path but no concrete add/edit/delete examples. asked for progress, asked for error details for debugging, and correctly called attention to command/adapter connection issues. Below are compact, practical patterns that fit a typical WinForms ADO.NET workflow and avoid repeating the original code.

Prefer explicit parameterized commands inside using blocks so connections are always disposed and SQL injection is prevented. Store the connection string in configuration rather than hard-coding. If sticking with a DataAdapter approach, set its InsertCommand/UpdateCommand/DeleteCommand and ensure each command has a Connection; otherwise execute standalone SqlCommand objects for single-row operations.

Insert (returns new identity), Update and Delete examples:

// Insert and return new identity
string sqlInsert = "INSERT INTO tblUsers (Name, Position) VALUES (@name, @pos); SELECT SCOPE_IDENTITY();";
using (var conn = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(sqlInsert, conn))
{
    cmd.Parameters.Add("@name", SqlDbType.NVarChar, 100).Value = txtUser.Text.Trim();
    cmd.Parameters.Add("@pos", SqlDbType.NVarChar, 100).Value = txtPosition.Text.Trim();
    conn.Open();
    var newId = cmd.ExecuteScalar();
    txtId.Text = (newId != null) ? Convert.ToInt32(newId).ToString() : "";
}
// Update
string sqlUpdate = "UPDATE tblUsers SET Name=@name, Position=@pos WHERE userID=@id";
using (var conn = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(sqlUpdate, conn))
{
    cmd.Parameters.Add("@name", SqlDbType.NVarChar, 100).Value = txtUser.Text.Trim();
    cmd.Parameters.Add("@pos", SqlDbType.NVarChar, 100).Value = txtPosition.Text.Trim();
    cmd.Parameters.Add("@id", SqlDbType.Int).Value = int.Parse(txtId.Text);
    conn.Open();
    int rows = cmd.ExecuteNonQuery();
}
// Delete
string sqlDelete = "DELETE FROM tblUsers WHERE userID=@id";
using (var conn = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(sqlDelete, conn))
{
    cmd.Parameters.Add("@id", SqlDbType.Int).Value = int.Parse(txtId.Text);
    conn.Open();
    cmd.ExecuteNonQuery();
}

Troubleshooting notes: always catch and log exceptions with full messages/stack traces (this helps others help, as suggested). Validate and parse textbox values before sending to the DB. For multi-step changes use transactions, and refresh the displayed data after any DML. For authoritative guidance on parameterized commands and ADO.NET patterns see ADO.NET commands and parameters.

Recommended Answers

All 5 Replies

hmmm, how far u have done?show the code and other member can correct any mistaken..

Please help me...here's so far I have...I need codes for add/edit/delete records....
thanx...

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string connectionString ="server=sroque\\sqlexpress;database=InventoryDB;uid=sa;pwd=ripple";

            SqlConnection mySqlConnection = new SqlConnection(connectionString);

            string selectString = "SELECT * FROM tblUsers";

            SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
            mySqlCommand.CommandText = selectString;
            SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();

            mySqlDataAdapter.SelectCommand = mySqlCommand;

            DataSet myDataSet = new DataSet();

            mySqlConnection.Open();

            string dataTableName = "tblUsers";
            mySqlDataAdapter.Fill(myDataSet, dataTableName);

            DataTable myDataTable = myDataSet.Tables[dataTableName];

            foreach (DataRow myDataRow in myDataTable.Rows)
            {
                txtId.Text = "" + myDataRow["userID"];
                txtUser.Text = "" + myDataRow["Name"];
                txtPosition.Text = "" + myDataRow["Position"];
            }
            mySqlConnection.Close();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (btnAdd.Text == "&Add")
            {
                txtId.Text = "";
                txtUser.Text = "";
                txtPosition.Text = "";
                btnAdd.Text = "&Save";
            }
            else if (btnAdd.Text == "&Save")
            {
                //then here I want to save records from the textbox to my database

            }
        }
    }
}

Please correct me if there's something wrong with my codes...It already have SQL Database connection and I successfully display my record from the database....

Please help me...here's so far I have...I need codes for data manipulation adding/edit/delete records....im using C#Windows Application

THANK YOU...you're a big help...

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
string connectionString ="server=sroque\\sqlexpress;database=InventoryDB;uid=sa;pwd=ripple";

SqlConnection mySqlConnection = new SqlConnection(connectionString);

string selectString = "SELECT * FROM tblUsers";

SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText = selectString;
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();

mySqlDataAdapter.SelectCommand = mySqlCommand;

DataSet myDataSet = new DataSet();

mySqlConnection.Open();

string dataTableName = "tblUsers";
mySqlDataAdapter.Fill(myDataSet, dataTableName);

DataTable myDataTable = myDataSet.Tables[dataTableName];

foreach (DataRow myDataRow in myDataTable.Rows)
{
txtId.Text = "" + myDataRow["userID"];
txtUser.Text = "" + myDataRow["Name"];
txtPosition.Text = "" + myDataRow["Position"];
}
mySqlConnection.Close();
}

private void btnAdd_Click(object sender, EventArgs e)
{
if (btnAdd.Text == "&Add")
{
txtId.Text = "";
txtUser.Text = "";
txtPosition.Text = "";
btnAdd.Text = "&Save";
}
else if (btnAdd.Text == "&Save")
{
//then here I want to save records from the textbox to my database

}
}
}
}

I can't debug your code or even read it, to make it easy, inform us with error raises when you run the code.

You forgot to assign the SqlConnection to your adapter.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.