[英]visually select datagridview cell
我正在嘗試將datagridview用作“標簽”網格。 我有許多要設置和編輯“標簽”的對象。 datagridview中的每個單元格都有一個字符串標簽,datagridview是多選的,因此用戶可以選擇很多標簽。
它非常適合設置標簽...
但是,我希望能夠對其進行編輯。 因此,當我加載datagridview時,我想以編程方式選擇與現有標簽相對應的單元格。
代碼很簡單:
public frmSaveQuery(string Name, string Description, string tagList, List<TagType> AllTags)
{
InitializeComponent();
TagList = AllTags;
Cancelled = true;
txtQueryName.Text = Name;
txtDescription.Text = Description;
string[] tags = tagList.Split(new string[] {"|"}, StringSplitOptions.RemoveEmptyEntries);
foreach (DataGridViewRow row in tagSelector.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (tags.Contains(cell.Value.ToString().ToUpper()))
{
cell.Selected = true;
}
else
{
cell.Selected = false;
}
}
}
foreach (DataGridViewRow row in tagSelector.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.Selected) Debug.WriteLine (cell.Value.ToString());
}
}
}
調試驗證單元被“選中”。 但是,在實際的datagridview上,它們在外觀上看起來不像所選單元格(即未突出顯示為藍色)。
任何想法如何使它們看起來在視覺上被選中?
在顯示控件之前,您無法將焦點設置到它們。
Shown
事件的事件處理程序是這樣做的好地方。 第一次顯示表單時,此事件僅引發一次( MSDN Form.Shown Event )。
您只需要保存tags
tagList
tags
值,以供以后在Shown
事件處理程序中使用
private String[] _Tags;
public frmSaveQuery(string Name,
string Description,
string tagList,
List<TagType> AllTags)
{
InitializeComponent();
TagList = AllTags;
Cancelled = true;
txtQueryName.Text = Name;
txtDescription.Text = Description;
//Save tags in the class variable
_Tags = tagList.Split(new string[] {"|"}, StringSplitOptions.RemoveEmptyEntries);
//Wiring up handler to the event
this.Shown += frmSaveQuery_Shown;
}
public void frmSaveQuery_Shown(Object sender, EventArgs e)
{
if (_Tags == null || _Tags.Length == 0)
return;
foreach (DataGridViewRow row in tagSelector.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (tags.Contains(cell.Value.ToString().ToUpper()))
{
cell.Selected = true;
}
else
{
cell.Selected = false;
}
}
}
foreach (DataGridViewRow row in tagSelector.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.Selected) Debug.WriteLine (cell.Value.ToString());
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.