c #datagridview doubleclick将数据加载到单独的表单中

时间:2017-01-30 11:22:08

标签: c# sql datagridview

enter image description here您好我有一个显示客户详细信息的主表单。我创建了一个单独的表单来搜索特定的客户。在doubleclick事件中,我希望将数据加载到主窗体中的一些文本框中并关闭我已经通过这个网站尝试了几件事但没有运气..

我在mainform中创建了这个函数来加载数据但是我不知道怎么从' searchform'中调用函数。并将所选行传递给SQL查询:

private void searchSelected()
    {
        {
            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "Select * from tbl_customers where custId = '" + custIdTxt.SelectedItem.ToString() + "'";
            cmd.ExecuteNonQuery();
            DataTable dt = new DataTable();
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            sda.Fill(dt);
            foreach (DataRow dr in dt.Rows)
            {
                custIdTxt.Text = (dr["custId"].ToString());
                custRefTxt.Text = (dr["custRef"].ToString());
                nameTxt.Text = (dr["name"].ToString());
                contactTxt.Text = (dr["contact"].ToString());
                telephoneTxt.Text = (dr["telephone"].ToString());

            }
            con.Close();
        }
    }

当用户选择他们希望查看详细信息的客户时,下面是双击功能:

private void searchResults_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
        this.Close();
    }

1 个答案:

答案 0 :(得分:0)

首先在mainform

上创建searchform变量
MainForm mainform;

然后在main form打开searchform之前写下这个以指定mainform

searchform srcform= new searchform();
srcform.mainform = this;
srcform.ShowDialog();

然后在双击事件中

private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgse)
{
     if(e.RowIndex > -1)
     {
          var row = dataGridView1.Rows[e.RowIndex];
          searchSelected(Convert.ToInt32(row["custId"].ToString()));
     }
 }

像这样改变searchSelected方法

private void searchSelected(int custId)
    {
        {
            //codes
            cmd.CommandText = "Select * from tbl_customers where custId = '" + custId   + "'";
            //codes
        }
    }