本文实例讲述了C#中DataGridView操作技巧。分享给大家供大家参考。具体分析如下:
///
/// 初始化DataGridView属性
///
/// 要处理的DataGridView
/// 允许用户添加行
/// 允许用户删除行
/// 是否显示包含行标题的列
/// 列标头高度大小模式
/// 是否多选
/// 是否只读
/// 列头宽度
/// 列选择模式
public virtual void InitSetDataGridViewAttribute(DataGridView dg,
bool allowUserToAddRows,
bool allowUserToDeleteRows,
bool allowUserToResizeRows,
bool rowHeadersVisible,
DataGridViewColumnHeadersHeightSizeMode columnHeadersHeightSizeMode,
bool multiSelect,
bool readOnly,
int rowHeadersWidth,
DataGridViewSelectionMode selectionMode)
{
dg.AllowUserToAddRows = allowUserToAddRows;
dg.AllowUserToDeleteRows = allowUserToDeleteRows;
dg.AllowUserToResizeRows = allowUserToResizeRows;
dg.RowHeadersVisible = rowHeadersVisible;
dg.ColumnHeadersHeightSizeMode = columnHeadersHeightSizeMode;
dg.MultiSelect = multiSelect;
dg.ReadOnly = readOnly;
dg.RowHeadersWidth = rowHeadersWidth;
dg.SelectionMode = selectionMode;
dg.RowStateChanged += dg_RowStateChanged;
}
///
/// 初始化DataGridView属性
///
/// 要处理的DataGridView
public virtual void InitSetDataGridViewAttribute(DataGridView dg)
{
InitSetDataGridViewAttribute(dg,
false,
false,
false,
true, DataGridViewColumnHeadersHeightSizeMode.AutoSize,
false,
true,
50,
DataGridViewSelectionMode.FullRowSelect);
}
///
///
///
///
///
public virtual void dg_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
{
e.Row.HeaderCell.Value = (e.Row.Index + 1).ToString();
}
///
/// DataGridView添加行
///
/// 要处理的DataGridView
/// 添加的列
public void DataGridViewAddRows(DataGridView dg, DataGridViewRow dr)
{
dg.Rows.Add(dr);
}
///
/// DataGridView行中添加列
///
/// 要添加的对象
///
public DataGridViewRow DataGridViewRowsAddCells(object[] objs)
{
DataGridViewRow row = new DataGridViewRow();
foreach (object obj in objs)
{
DataGridViewTextBoxCell tBoxCell = new DataGridViewTextBoxCell();
tBoxCell.Value = obj;
row.Cells.Add(tBoxCell);
}
return row;
}
///
/// DataGridView添加行
///
/// 要处理的DataGridView
/// 添加的对象List
public void DataGridViewAddRows(DataGridView dg, List
DataGridViewAddRows(dg, dr);
}
}
///
/// DataGridView添加行
///
/// 要处理的DataGridView
/// 添加的对象
public void DataGridViewAddRows(DataGridView dg, object[] objs)
{
DataGridViewRow dr = DataGridViewRowsAddCells(objs);
DataGridViewAddRows(dg, dr);
}
///
/// DataGridView列排序
///
/// 要排序的DataGridView
/// 列索引
/// 0:升序排列 1:降序排列
public void DataGridViewSort(DataGridView dg, int dataGridViewColumnIndex, int flag)
{
switch (flag)
{
case 0:
dg.Sort(dg.Columns[dataGridViewColumnIndex], ListSortDirection.Ascending);
break;
case 1:
dg.Sort(dg.Columns[dataGridViewColumnIndex], ListSortDirection.Descending);
break;
default:
break;
}
}
#endregion
希望本文所述对大家的C#程序设计有所帮助。