[英]How to get the data when I select a datagridview cell or column
我在Windows Forms應用程序中有2個datagridview控件。
當我選擇第一個datagridview單元格或下一個datagridview的行時,我想獲取一個人的信息:
try
{
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
con.Open();
adap3 = new SqlDataAdapter(@"SELECT Date,Attendance,Remarks FROM dailyattendance where employee_id='"+DailyGV.CurrentRow+"'", con);
ds3 = new DataSet();
adap3.Fill(ds3, "dailyattendance");
dataGridView1.DataSource = ds3.Tables[0];
}
我正在嘗試上面的代碼。 但這不起作用。
我不太確定DailyGV.CurrentRow
是什么,但是基本上您可以使用RowHeaderMouseClick
...請參閱MSDN文檔 。 要使用它,請在初始化表單組件時將事件處理程序掛鈎到它(您也可以使用VS設計器...
dataGridView1.RowHeaderMouseClick += dataGridView1_RowHeaderMouseClick;
void dataGridView1_RowHeaderMouseClick(
object sender, DataGridViewCellMouseEventArgs e)
{
}
每當您在DataGridView
控件中選擇一個行標題時,都會觸發該事件處理程序,該DataGridView
將通過DataGridViewCellMouseEventArgs
類的實例傳遞有關事件的信息(請參閱MSDN文檔 )。 此參數具有RowIndex
屬性,該屬性提供所單擊行的索引,您可以使用該索引來檢索該行中單元格的值...包括人員ID(如果提供)...例如。
void dataGridView1_RowHeaderMouseClick(
object sender, DataGridViewCellMouseEventArgs e)
{
string personId = dataGridView1.Rows[e.RowIndex].Cells["PersonId"].Value;
//TODO: implement your own query to retrieve data for that person id
}
請注意,在訪問單元格集合索引器時,您需要提供適當的列名。Cells Cells["columnName"]
由於Leo和Arsalan Bhatti已經提出了解決方案,因此我將不提供任何解決方案的描述。 我只是在告訴您您的代碼應該是什么樣子以及應該如何編寫。
string connectionString = consettings.ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
con.Open();
string empID = DailyGV.CurrentRow.Cells["employee_id"].Value.ToString();
SqlCommand Cmd = con.CreateCommand();
Cmd.CommandText = "SELECT Date,Attendance,Remarks FROM dailyattendance where employee_id=@employee_id";
Cmd.Parameters.Add("@employee_id", SqlDbType.Int).Value = Int32.Parse(empID);
adap3 = new SqlDataAdapter(Cmd);
DataTable dt = new DataTable();
adap3.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
catch
{}
}
try
{
cn.Open();
string query = "select employee_id,Employee_Name,Image_of_Employee from Employee_Details where employee_id='" + dataGridView1.SelectedCells[0].Value.ToString() + "'";
SqlCommand cmd = new SqlCommand(query, cn);
SqlDataReader sdr;
sdr = cmd.ExecuteReader();
if (sdr.Read())
{
string aa = (string)sdr["employee_id"];
string bb = (string)sdr["employee_name"];
txtEmployeeID.Text = aa.ToString();
txtnameofemployee.Text = bb.ToString();
byte[] img=(byte[])sdr["Image_of_employee"];
MemoryStream ms=new MemoryStream(img);
ms.Seek(0,SeekOrigin.Begin);
pictureBox1.Image=Image.FromStream(ms); cn.Close();
}
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
您正在SELECT查詢中將當前行的索引作為員工ID傳遞。 傳遞所選記錄的員工ID。 然后它將正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.