使用列號訪問DataGrid中的列引起的問題,datagrid

來源:互聯網
上載者:User

使用列號訪問DataGrid中的列引起的問題,datagrid

問題描述

WPF應用程式中,使用DataGrid來顯示員工資訊,包含公司名稱,姓名,年齡,電話四列。而在某些情況下,電話列需要被隱藏,所以在畫面的後端代碼中使用下面的代碼來控制電話列的顯示情況。

if (isShowTelephone){    this.DataGrid_People.Columns[3].Visibility = Visibility.Visible;}else{    this.DataGrid_People.Columns[3].Visibility = Visibility.Collapsed;}
當然,使用這些代碼可以達到想要的效果。只是,這裡存在一個隱患:倘若後面的開發人員在電話列的前面增加或者刪除了若干列的話,再去執行我們的代碼就會出問題,因為此時的this.DataGrid_People.Columns[3]指的就不再是電話列,那麼控制電話列顯示的代碼就變成了控制其他列顯示的代碼,該隱藏的可能沒有被隱藏,而該顯示的可能沒有被正常顯示。

 

解決方案

為電話列指定Name,使用Name來訪問電話列,假設將電話列命名為Columns_Telephone,那麼控制電話列顯示的代碼可以修改為:

if (isShowTelephone){    this.Columns_Telephone.Visibility = Visibility.Visible;}else{    this.Columns_Telephone.Visibility = Visibility.Collapsed;}
這樣一來,再在電話列前面增加或者刪除列時,就不會影響到這部分代碼的正確執行了。


看到你回答的給datagridview 添加序號列的問題 教一下

你可以在資料繫結或者行數有很大變化時測量一下DataGridView最大行數的行數的寬度然後在繪製 代碼如下
SolidBrush solidBrush;
StringFormat stringFormat = new StringFormat();
private void Form36_Load(object sender, EventArgs e)
{
solidBrush = new SolidBrush(dataGridView1.RowHeadersDefaultCellStyle.ForeColor);
stringFormat.Alignment = StringAlignment.Center;//垂直置中
stringFormat.LineAlignment = StringAlignment.Center;//水平置中
stringFormat.FormatFlags = StringFormatFlags.NoWrap;//不自動換行
DataTable dataTable = new DataTable();
dataTable.Columns.Add("AA");
for (int i = 0; i < 111111; i++)
{
dataTable.Rows.Add(new object[] { i});
}
dataGridView1.DataSource = dataTable;
SetRowHeadersWidth();//在資料來源改變或者行數有很大變化時調用這個方法
}
private void SetRowHeadersWidth()
{
int line = dataGridView1.Rows.Count;
Size size = TextRenderer.MeasureText(line.ToString(), dataGridView1.RowHeadersDefaultCellStyle.Font);//測試dataGridView1行數的寬度
dataGridView1.RowHeadersWidth = size.Width + 30;//設定左側行的寬度
}
private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
//在左側行中間繪製
e.Graphics.DrawString((e.RowIndex + 1).ToString(),
e.InheritedRowStyle.Font,
solid......餘下全文>>

 
winform 中DataGridView列的順序問題

你把student 類裡面欄位Age和Address換一下試試,因為dgv2和它是一致的。

另外,dgv1的顯示和編輯列的順序一致嗎?還是和dgv2(student 類)的顯示欄位一致?
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.