Thursday, August 13, 2009

DataGridView - Extracting the Contents of Currently Selected Row

One of the common requirement is CRUD operation is extracting the contents of the currently selected row in a Grid to be updated in TextBoxes or other controls.

SqlConnection cnn;
SqlDataAdapter da;
DataSet ds = new DataSet();
private void Form1_Load(object sender, EventArgs e)
{
cnn = new SqlConnection("Integrated Security=sspi;Initial catalog=Northwind");
cnn.Open();
da = new SqlDataAdapter("select CategoryId, CategoryName, Description from Categories", cnn);
da.Fill(ds, "Cat");
dataGridView1.DataSource = ds.Tables["Cat"];
}



private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
listBox1.Items.Clear();
for (int colindex = 0; colindex < dataGridView1.Columns.Count ; colindex++)
{
listBox1.Items.Add(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[colindex].Value.ToString());
}
}




















DataGridView ComboBox Placing and Child Table Insertion



SqlConnection cnn;
SqlDataAdapter da;
DataSet ds = new DataSet();

SqlCommand cmd;
SqlDataReader dre;

DataGridViewTextBoxColumn newCol;
DataGridViewComboBoxColumn cboCol;

private void Form1_Load(object sender, EventArgs e)
{
cnn = new SqlConnection("Integrated security=sspi;INitial Catalog=ContactManagement;Data Source=.\\shalvin");
cnn.Open();

da = new SqlDataAdapter("select * from ContactGroups", cnn);
da.Fill(ds, "Grp");

CreateGridViewColumns();
}

private void CreateGridViewColumns()
{
cboCol = new DataGridViewComboBoxColumn();
cboCol.DataSource = ds.Tables["Grp"];
cboCol.DisplayMember = "GroupName";
dataGridView1.Columns.Add(cboCol);

newCol = new DataGridViewTextBoxColumn();
dataGridView1.Columns.Add(newCol);

}



private void btnSave_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
string strGroupId = "";
DataGridViewRow row = dataGridView1.Rows[i];

string strSql;
strSql = "select GroupId from ContactGroups where GroupName= '"
+ row.Cells[0].Value.ToString() + "'";

cmd = new SqlCommand(strSql, cnn);
dre = cmd.ExecuteReader();
while(dre.Read())
strGroupId = dre["GroupId"].ToString();
dre.Close();


cmd = new SqlCommand("Insert into Contacts (GroupId, ContactName) values ('" + strGroupId + "', '" + row.Cells[1].Value.ToString() + "')", cnn);
cmd.ExecuteNonQuery();
}

MessageBox.Show("Record saved");
}




Related Blog
Windows Forms ListView
Filling Windows Forms ListView with DataTable

1 comment:

  1. please give me code project combobox in datagridview. thanks
    my email : ngoisaomayman_cun@yahoo.com

    ReplyDelete