Abid Ali
Abid Ali

Reputation: 1747

when i am inserting a single record, it inserts two records at a time. help please

    private void button1_Click(object sender, EventArgs e)
    {
        Insert();
    }

    private int Insert()
    {
        string Query = "insert into person values ('" + textBox4.Text + "','" + textBox5.Text + "')";
        string connectionString = @"Data Source=COMPAQ-PC-PC\SQLEXPRESS;Initial Catalog=prac;Integrated Security=True";
        SqlConnection cn = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(Query, cn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        if (cn.State == ConnectionState.Closed)
        {
            cn.Open();
        }
        DataTable dt = new DataTable();
        da.Fill(dt);
        int RowEffected = cmd.ExecuteNonQuery();
        cn.Dispose();
        if (RowEffected > 0)
        {
            MessageBox.Show("Record Affected");
        }
        GetDBConnection();
        if (cn.State == ConnectionState.Open)
        {
            cn.Close();
        }
        return 0;
    }



    public Form1()
    {
        InitializeComponent();
        GetDBConnection();
        //Insert();
    }

    private void GetDBConnection()
    {
        string connnectionstring = @"Data Source=COMPAQ-PC-PC\SQLEXPRESS;Initial Catalog=prac;Integrated Security=True";
        SqlDataAdapter da = new SqlDataAdapter("select * from person", connnectionstring);
        DataTable dt = new DataTable();
        da.Fill(dt);
        dataGridView1.DataSource = dt.DefaultView;
        comboBox1.DataSource = dt;
        comboBox1.ValueMember = "id";
        comboBox1.DisplayMember = "lname";

    }

Upvotes: 0

Views: 83

Answers (1)

royas
royas

Reputation: 4936

When you do da.Fill(dt); cmd passed to da in it's constructor is executed. That's first time. Second is in ExecuteNonQuery. Cmd in sqlDataAdapter should be SELECT command.

Upvotes: 5

Related Questions