![](/img/trans.png)
[英]Check for column datatypes on a on a datagridview that is not bound to a datasource in C#
[英]c# clear datagridview bound to datasource
我有一個綁定到數據源的datagridview,所有標頭都添加到具有datapropertyname設置的列集合中。
當我使用清除datagridview時
DataGridView1.DataSource = null;
標頭也消失了,當我再次填充datagridview時,標頭文本就是數據庫列名。 如何在不刪除標題的情況下清除綁定的datagridview?
你可以用這個
if (dataGridViewNotas.DataSource != null)
((DataTable) dataGridViewNotas.DataSource).Rows.Clear();
解決此問題的方法之一是使用集合作為數據源,
創建一個具有代表數據源的屬性的類(每個屬性將代表數據庫中的一列)
public class Student
{
public string Name { get; set; }
public string Address { get; set; }
}
您需要手動將列添加到datagridview並為每列設置相關的DataPropertyName
並設置HeaderText
。 從數據庫加載數據時,首先將此數據填充到列表中。 因此,您將擁有一個List<Student>
。
List<Student> studentDetail = new List<Student>();
將此設置為datagridview的數據源。
dataGridView1.DataSource = studentDetail;
清除數據源
要清除網格的數據源,只需創建一個空的Student列表,然后再次將其設置為數據源。 當您進行類似設置時,將保留每列的標題。
List<Student> emptyStudentDetail = new List<Student>();
dataGridView1.DataSource = emptyStudentDetail;
如果您不想使用對象集合,而仍然使用this.dataGridView1.DataSource = null;
刷新數據源this.dataGridView1.DataSource = null;
然后嘗試這種方法:
假設您正在使用數據集DataSet或本地數據庫。 每次將dataGridView與新數據源綁定之前,請創建未綁定的列,這些列的名稱應與數據源的名稱相同。 創建它們之后,您應該隱藏它們,因為刷新dataGridView的數據源時將需要它們。 下面的示例代碼知道數據源列的名稱,因此它們是硬編碼的,但是如果有必要,您可以每次遍歷數據源並創建未綁定列的新集合。
private void Form1_Load(object sender, EventArgs e)
{
this.dataGridView1.DataSource = GetDataSet();
this.dataGridView1.DataMember = "Students";
this.dataGridView1.Columns.Add("unboundColumn1", "ID");
this.dataGridView1.Columns.Add("unboundColumn2", "Name");
this.dataGridView1.Columns["unboundColumn1"].Visible = false;
this.dataGridView1.Columns["unboundColumn2"].Visible = false;
}
private void button1_Click(object sender, EventArgs e)
{
this.dataGridView1.Columns["unboundColumn1"].Visible = true;
this.dataGridView1.Columns["unboundColumn2"].Visible = true;
this.dataGridView1.DataSource = null;
}
private DataSet GetDataSet()
{
DataSet dataSet = new DataSet();
dataSet.Tables.Add("Students");
dataSet.Tables["Students"].Columns.Add("ID", typeof(int));
dataSet.Tables["Students"].Columns.Add("Name", typeof(string));
dataSet.Tables["Students"].Rows.Add(1, "John Joy");
dataSet.Tables["Students"].Rows.Add(2, "Ivan Nova");
dataSet.Tables["Students"].Rows.Add(3, "Michael German");
return dataSet;
}
奮斗了24小時。 不知道為什么它能工作,但是沒有對我產生運行時錯誤的解決方案是處置與datagridview關聯的表適配器:
if (this.dataTableTableAdapter != null)
{
this.dataTableTableAdapter.Dispose();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.