Flanker
Flanker

Reputation: 89

how to set the value of a text box cell on previous cell leave event in data gridview

I am using data grid view for accepting data from user. I have added 3 columns in data grid view:

  1. S.no. (Serial number: Auto generated field: text box column)
  2. acname (Account name: Select Names from a table on on load event: combo box column)
  3. code (code : SHOULD SELECT THE CODE OF THAT NAME WHICH IS SELECTED IN COMBO BOX CELL : text box column)

I am working with cell leave event and I have selected the required data as per name selected in combo box cell.

I am using the following code:

 private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
 {

    if (e.ColumnIndex== 1)
    {
        string name= dataGridView1.CurrentCell.EditedFormattedValue.ToString();
        SqlConnection c = new SqlConnection(); 
            c.ConnectionString = "Data              Source=.\\SQLEXPRESS;AttachDbFilename='D:\\Documents\\
         Visual Studio 2008\\Projects\\
        test\\test\\Database1.mdf';Integrated Security=True;User Instance=True";
        c.Open();
        string q = "select code from test where name ='"+name+"'";
        SqlCommand cmd = new SqlCommand(q, c);
        SqlDataReader dr = cmd.ExecuteReader();
 DataGridViewTextBoxColumn cod = dataGridView1.Columns[2] as DataGridViewTextBoxColumn;
        while (dr.Read())
        {
            int code = dr.GetInt32(0);
            MessageBox.Show(code.ToString());
        }
    }
 }

So above code is running perfectly and in last message box it shows the respective code of the name selected in the combo box.

I want that as soon as combo box cell loose focus the next cell automatically take required code.

Upvotes: 1

Views: 1299

Answers (1)

PrfctByDsgn
PrfctByDsgn

Reputation: 1050

you could just replace your MessageBox.Show with

dataGridView1.Rows[e.RowIndex].Cells[2].Value = code;

also you could replace your SqlDataReader with a call to cmd.ExecuteScalar ... and use a SqlParameter instead of constructing the where condition dynamically ... if you want to improve your code ...

sample for using ExecuteScalar:

using (var c = new SqlConnection())
{ 
    using (var cmd = new SqlCommand("select code from test where name = @name", c))
    {
        cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = name;

        c.Open();
        int code = (int)cmd.ExecuteScalar();
    }
}

I suggest to add some exception handling code also ...

Upvotes: 1

Related Questions