Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在DataGridView中自动生成编号_C#_Winforms_Datagridview - Fatal编程技术网

C# 在DataGridView中自动生成编号

C# 在DataGridView中自动生成编号,c#,winforms,datagridview,C#,Winforms,Datagridview,我有一个DataGridView并将其绑定到数据库 我在DataGridView中使用以下代码自动创建行号: dgv.Rows[e.RowIndex].Cells[0].Value = e.RowIndex +1; 但结果并不好。请帮我建立这个号码 更新: 结果: 所以最后两行不显示数字。您可以在标题单元格中显示 DataGridView gridView = sender as DataGridView; if (null != gridView) { fo

我有一个DataGridView并将其绑定到数据库

我在DataGridView中使用以下代码自动创建行号:

dgv.Rows[e.RowIndex].Cells[0].Value = e.RowIndex +1;
但结果并不好。请帮我建立这个号码

更新: 结果:


所以最后两行不显示数字。

您可以在标题单元格中显示

DataGridView gridView = sender as DataGridView;

    if (null != gridView)
    {
        foreach (DataGridViewRow r in gridView.Rows)
        {
            gridView.Rows[r.Index].HeaderCell.Value = (r.Index + 1).ToString();
        }
    }

RowsAdded
事件对此不起作用-尝试将一些调试输出添加到事件处理程序中,您将看到该事件是针对多组行而不是单个行触发的,这就是为什么只填充前两个值的原因

执行此操作的更好位置是
DataBindingComplete
DefaultValuesNeeded
事件

DataBindingComplete
将填充第一次加载时的所有值,然后
DefaultValuesNeeded
将填充每一新行

数据绑定完成:

void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    foreach (DataGridViewRow r in dataGridView1.Rows)
    {
        r.Cells["AutoGenColumn"].Value = r.Index + 1;
    }
}
所需的默认值:

void dataGridView1_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
{
    dataGridView1.Rows[e.Row.Index].Cells["AutoGenColumn"].Value = e.Row.Index + 1;
}

这一要求似乎有点不寻常——您没有解释为什么需要这个数字,但您可能希望将行添加到基础数据集中(例如,使用DataTable非常容易),或者按照Subek的建议将行添加到行标题中



最后要注意的一点是,这种自动生成的列通常最好在
cellvalizing
事件中完成,例如,当您和一个列相加时,其中两个列相加。这在这里不起作用,因为你的专栏不是以其他专栏为基础的,但值得一提的是,这是一种普遍的做法。

我认为这是最简单的,对我来说100%有效

<asp:TemplateField HeaderText="Sl. No.">
   <ItemTemplate>
       <%# Container.DataItemIndex + 1 %>
   </ItemTemplate>
</asp:TemplateField>

这将起作用

public Form1()
{
    ... ...
    gridView.RowStateChanged += GridView_RowStateChanged;
}

private void GridView_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
{
    (sender as DataGridView).Rows[e.Row.Index].Cells[0].Value = e.Row.Index + 1;
}


我第一次尝试了
RowsAdded
事件,但对于新添加的行,它无法正常工作。

salam。WindowsForms或Asp.NET?看来您的方法是最简单的方法,并且工作正常。在结果自动编号中不显示所有数字。在哪里使用此代码??我使用dgv_RowsAdded(…)中的代码。没关系??它很管用,伙计,如果你想找别的东西,请告诉我
public Form1()
{
    ... ...
    gridView.RowStateChanged += GridView_RowStateChanged;
}

private void GridView_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
{
    (sender as DataGridView).Rows[e.Row.Index].Cells[0].Value = e.Row.Index + 1;
}