合并2个数据表列的数据并在datagridview中显示为1列

时间:2013-10-04 06:21:05

标签: c# datagridview datatable oledb

这是我的查询

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");

3 个答案:

答案 0 :(得分: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;
        }
    }
}

答案 1 :(得分:0)

尝试做这样的事情

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

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

答案 2 :(得分:0)

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

将您的查询更改为

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

您可以参考this