0

这是我的查询

cmd2 = new OleDbCommand("Select TOP " + PageSize + " PatientID,PFirstName,PLastName,RegDate,MobileNo,PEmailID from Patient_Registration ORDER BY PatientID", con);

我正在用这个填充数据表cmd2

// con.Open();
this.adp1.SelectCommand = cmd2;
this.adp1.Fill(dt);

现在我想合并PFirstName,PLastName列,以便我可以将它们显示为 datagridview 中的一列,我该怎么做我试过这样的东西,但它不起作用

dt.Columns.Add("FullName", typeof(string), "PFirstName + ' ' + PLastName");
4

3 回答 3

1

您可以将全名列添加到 DataGridView 并在DataBindingComplete事件中手动设置。

像这样:

DataTable dt;
private void Form1_Load(object sender, EventArgs e)
{
    // sample data
    dt = new DataTable();
    dt.Columns.Add("FirstName", typeof(string));
    dt.Columns.Add("LastName", typeof(string));
    dt.Columns.Add("Age", typeof(int));

    dt.Rows.Add(new object[] { "Andrew", "Jones", 5 });
    dt.Rows.Add(new object[] { "Steve", "Jobs", 15 });
    dt.Rows.Add(new object[] { "Surendar", "Sani", 10 });

    dataGridView1.AutoGenerateColumns = false;

    // Make DataGridView columns
    DataGridViewTextBoxColumn dgvtxtFullName = new DataGridViewTextBoxColumn();
    dgvtxtFullName.HeaderText = "Full Name";

    DataGridViewTextBoxColumn dgvAge = new DataGridViewTextBoxColumn();
    dgvAge.HeaderText = "Age";
    dgvAge.DataPropertyName = "Age";

    dataGridView1.Columns.Add(dgvtxtFullName);
    dataGridView1.Columns.Add(dgvAge);

    dataGridView1.DataSource = dt;
}

private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    // Loop through each DataGridViewRow to set the full name column
    foreach (DataGridViewRow item in dataGridView1.Rows)
    {
        if (!item.IsNewRow)
        {
            string FullName = string.Format("{0} {1}",
                dt.Rows[item.Index]["FirstName"], dt.Rows[item.Index]["LastName"]);
            item.Cells[0].Value = FullName;
        }
    }
}
于 2013-10-04T06:57:37.897 回答
0

尝试做这样的事情

cmd2 = new OleDbCommand("Select TOP " + PageSize + " PatientID,PFirstName&' '&PLastName as 'Full Name',RegDate,MobileNo,PEmailID from Patient_Registration ORDER BY PatientID", con);

这是 sql fiddle 链接供参考http://www.sqlfiddle.com/#!3/abc6b/1

于 2013-10-04T06:32:59.347 回答
0

连接字符串的语法是&您可以在查询本身中执行此操作。

将您的查询更改为

cmd2 = new OleDbCommand("Select TOP " + PageSize + " PatientID,[PFirstName]&" "&[ PLastName] as [Full Name],RegDate,MobileNo,PEmailID from Patient_Registration ORDER BY PatientID", con);

你可以参考这个

于 2013-10-04T06:34:09.117 回答