WinForm中datagridview无法取消默认选中行的问题。
窗体是MID子窗体。
在窗体载入事件中使用以下方法都无效。
dgvFittingsList.ClearSelection();//无效
dgvFittingsList.CurrentCell = null;//无效
dgvFittingsList.Rows[0].Selected = false;//无效
如果放到一个按钮中,点击则有效。
代码很简单如下:
public partial class Fittings : Form
{
private int ProductsID = 120;
public Fittings()
{
InitializeComponent();
}
private void Fittings_Load(object sender, EventArgs e)
{
dgvFittingsList.AutoGenerateColumns = false;
getFittingsList(ProductsID);
dgvFittingsList.ClearSelection();//无效
dgvFittingsList.CurrentCell = null;//无效
dgvFittingsList.Rows[0].Selected = false;//无效
}
/// <summary>
/// 根据产品ID读取配件数据
/// </summary>
/// <param name="ProductID">产品ID</param>
private void getFittingsList(int ProductID)
{
DataSet ds = new DataSet();
ds = BLL.Fittings.Fittings.getFittings(ProductID);
dgvFittingsList.DataSource = ds.Tables[0];
dgvFittingsList.AlternatingRowsDefaultCellStyle.BackColor = Color.LightGray;//奇数行背景色
}
private void dgvFittingsList_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dgvFittingsList.Columns[e.ColumnIndex].Name.Equals("是否原装"))//重定义"是否原装"列的值
{
e.FormattingApplied = true;
DataGridViewRow row = dgvFittingsList.Rows[e.RowIndex];
string strValue = row.Cells["是否原装"].Value.ToString();
switch (strValue)
{
case "0":
e.Value = "否";
break;
case "1":
e.Value = "是";
break;
}
}
}
//列表右键菜单
private void dgvFittingsList_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
if (e.RowIndex >= 0)
{
//若行已是选中状态就不再进行设置
if (dgvFittingsList.Rows[e.RowIndex].Selected == false)
{
dgvFittingsList.ClearSelection();
dgvFittingsList.Rows[e.RowIndex].Selected = true;
}
//只选中一行时设置活动单元格
if (dgvFittingsList.SelectedRows.Count == 1)
{
dgvFittingsList.CurrentCell = dgvFittingsList.Rows[e.RowIndex].Cells[e.ColumnIndex];
}
//弹出操作菜单
contextMenuStrip1.Show(MousePosition.X, MousePosition.Y);
}
}
}
}