Help with DataGridView and C#

G

Guest

Need some help. I am using datagridview in 2005 with C#. I am calling a web
service and filling the datagridview with the data returned. This all works
fine. Next step is to take a value from one of the cells in the datagridview
and return it back with some other values in an object for another webservice
call. The problem is I dont know how to access a cell in a datagridview to do
this. Im pretty sure you have to do it thru the binding source for the
datagridview but I dont know how. I have the datagridview setup for no
multiselect so only one row can be selected and I know I will probably need
to write something to return which row is selected in the gridview and send
it to the bindingsource to tell it and return the value in the cell I need.
Can someone help please or send me to the right place to learn this seemingly
easy task. I have looked at the documentation for DataGridView and cant seem
to grasp it Thanks.
 
J

John J. Hughes II

dataGridView1.CurrentRow.Cells[<cell index>].value /// will get you the
value of a cell in the currently selected row.

foreach(DataGridViewRow row in dtaGridView1.SelectedRows)
row.Cells[<cell index>].value; /// gives you the value of a cell in a
group of rows.

I do the following on the DataGridRow delete event to check if the row is
used: You could use another event and just send the data instead of
checking delete.

private void dgMessageList_UserDeletingRow(object sender,
DataGridViewRowCancelEventArgs e)
{
e.Cancel =
this.CheckDelete(e.Row.Cells[this.idxDataGridViewTextBoxColumn.Index].Value);
}

private bool CheckDelete(object msgIdx)
{
try
{
Utils.MiscFuns.OpenConnection(this.sqlConnection1, true, "App1");
using (System.Data.SqlClient.SqlCommand cmd =
this.sqlConnection1.CreateCommand())
{
cmd.CommandText = "SELECT COUNT(*) FROM Directories WHERE
[MessagesIdx] = @MsgIdx";
cmd.Parameters.Add("@MsgIdx", SqlDbType.Int);
cmd.Parameters["@MsgIdx"].Value = msgIdx;
object cnt = cmd.ExecuteScalar();
if (cnt is int)
{
if ((int)cnt == 0)
return false;
else
MessageBox.Show(string.Format("Unable to delete message,
used by {0} module", cnt));
}
else
throw new Exception("Invalid return type");
}
}
catch (Exception ex)
{
Utils.frmError.ShowError("Unable to delete message", ex);
}
finally
{
this.sqlConnection1.Close();
}

return true;
}


Regards,
John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top