2013-10-04 96 views
0

顯示爲1列這是我的查詢合併2個數據表列的數據,並在datatgridview

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

嘗試這樣做,在您的查詢'OledDbCommand' –

+0

@ SaghirA.Khatri我不知道該怎麼做,在查詢時,你能Plaese顯示代碼 – Durga

回答

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

它不是SQL它是MS ACCESS請參考http://www.techonthenet.com/access/functions/string/concat.php – Rohit

+0

Downvoter有什麼理由? 做檢查小提琴鏈接的參考 –

+0

看到我的代碼是爲MS ACCESS現在太.. .. p –

0

來連接字符串是&你能做的語法,在您的查詢本身。

您的查詢更改爲

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

你可以參考this

+1

您的代碼不會給出任何空間,如FirstName和LastNname所要求的那樣... –

+0

@ SaghirA.Khatri請確認我的更新回答 – Rohit

+0

在你編輯Sir之後:)我也可以這麼做:p –

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; 
     } 
    } 
}