您在 cmets 中提到您希望最后一行填充颜色,并且在编辑时颜色也应该存在,并且您希望在通过 Dataset 检索数据时发生这些事情。您还希望在加载表单时关注最后一个可编辑行。
.
.
尝试在单独的项目文件中使用代码,以便您可以看到它是如何工作的。这样做时,创建一个空项目并添加一个 dataGridView1。
public partial class Form1 : Form
{
DataSet dSet = new DataSet();
public Form1()
{
InitializeComponent();
this.Shown += Form1_Shown;
dataGridView1.AllowUserToAddRows = false;
dataGridView1.CellBeginEdit += dataGridView1_CellBeginEdit;
dataGridView1.RowStateChanged += dataGridView1_RowStateChanged;
dSet = fillDataSet();
dataGridView1.DataSource = dSet.Tables[0].DefaultView;
dSet.Tables[0].Rows.Add();
}
void Form1_Shown(object sender, EventArgs e)
{
dataGridView1.CurrentCell = dataGridView1[0, dataGridView1.Rows.Count - 1];
dataGridView1.BeginEdit(false);
}
DataSet fillDataSet()
{
DataSet dSet = new DataSet();
dSet = new DataSet();
DataTable table = new DataTable("Names");
table.Columns.Add("ID");
table.Columns.Add("Name");
table.Columns.Add("Gender");
table.Rows.Add(new object[] { 1, "Salim", "Male" });
table.Rows.Add(new object[] { 2, "Salim", "Male" });
table.Rows.Add(new object[] { 3, "Salim", "Male" });
table.Rows.Add(new object[] { 4, "Salim", "Male" });
table.Rows.Add(new object[] { 5, "Salim", "Male" });
table.Rows.Add(new object[] { 6, "Salim", "Male" });
table.Rows.Add(new object[] { 7, "Salim", "Male" });
table.Rows.Add(new object[] { 8, "Salim", "Male" });
dSet.Tables.Add(table);
return dSet;
}
void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
if (e.ColumnIndex == dSet.Tables[0].Columns.Count - 1)dSet.Tables[0].Rows.Add();
}
private void dataGridView1_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
{
try
{
String ssNair = e.StateChanged.ToString();
if (e.Row.Index > 0)
dataGridView1.Rows[e.Row.Index - 1].DefaultCellStyle.BackColor = Color.White;
dataGridView1.Rows[e.Row.Index].DefaultCellStyle.BackColor = Color.Yellow;
}
catch { }
}
}
对于您需要的选项类型,您应该将 AllowUsersToAddRows 属性设置为 false,并根据某些条件添加行。
我在这里添加一个新行,而最后一行的最后一列正在被编辑。
当您与数据集绑定时,无法通过 dataGridView1.Rows.Add() 直接添加行;所以这里的行是使用 DataTable.Rows.Add() 方法添加的。
而且 DataGridView.RowsAdded 事件在使用 Dataset 填充数据时也不起作用,因此使用了 DataGridView.RowStateChanged 事件