Monday, May 26, 2008

DataGridViewHelper class

DataGridView这个控件在开发中经常会被用到, C#的组件总觉得不如Delphi组件那么容易使用, 怎样在Grid上选择一个Row, 怎样选择一个Cell, 我就被block了好久. 下面是代码:


namespace LiuHarry.Utils.Components
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;

public class DataGridViewHelper
{
private DataGridView m_DataGridView;
private SortedList<string, string> m_MapListFieldColumn = new SortedList<string, string>();
private DataView m_ShowedDataViewInGrid;

public DataGridViewHelper(DataGridView dataGridView, DataView showedDataViewInGrid)
{
this.m_DataGridView = dataGridView;
this.m_ShowedDataViewInGrid = showedDataViewInGrid;
this.InitFieldColumnMapList();
}

private string _GetGridViewColumnName(string dataFieldName)
{
for (int i = 0; i < this.m_DataGridView.Columns.Count; i++)
{
if (this.m_DataGridView.Columns[i].DataPropertyName == dataFieldName)
{
return this.m_DataGridView.Columns[i].Name;
}
}
return "";
}

private void InitFieldColumnMapList()
{
this.m_MapListFieldColumn.Clear();
for (int i = 0; i < this.m_ShowedDataViewInGrid.Table.Columns.Count; i++)
{
string columnName = this.m_ShowedDataViewInGrid.Table.Columns[i].ColumnName;
string str2 = this._GetGridViewColumnName(columnName);
this.m_MapListFieldColumn.Add(columnName, str2);
}
}

public string QuickFindGridViewColumnName(string dataFieldName)
{
int num = this.m_MapListFieldColumn.IndexOfKey(dataFieldName);
if (num < 0)
{
throw new Exception("There no a column in DataGridView corresponding DataFieldName=" + dataFieldName);
}
return this.m_MapListFieldColumn.Values[num];
}

public void SelectAndScrollToCell(string fieldName, object fieldValue)
{
this.m_DataGridView.ClearSelection();
if ((fieldName != null) && (fieldValue != null))
{
string str = this.QuickFindGridViewColumnName(fieldName);
foreach (DataGridViewRow row in (IEnumerable) this.m_DataGridView.Rows)
{
if (object.Equals(row.Cells[str].Value, fieldValue))
{
this.m_DataGridView.CurrentCell = row.Cells[str];
this.m_DataGridView.CurrentCell.Selected = true;
break;
}
}
}
}

public void SelectRow(object valueOfSortedField)
{
DataView showedDataViewInGrid = this.m_ShowedDataViewInGrid;
this.m_DataGridView.ClearSelection();
if ((showedDataViewInGrid != null) && (valueOfSortedField != null))
{
int num = showedDataViewInGrid.Find(valueOfSortedField);
if (num >= 0)
{
this.m_DataGridView.Rows[num].Selected = true;
}
}
}

public SortedList<string, string> MapListFieldColumn
{
get
{
return this.m_MapListFieldColumn;
}
}
}
}

No comments: