我可以';t更改Gridview中的列值

本文关键字:Gridview 更改 我可以 | 更新日期: 2023-09-27 17:58:53

我正试图在C#中的datagridview控件中插入一个自动编号列。

一切都很好,但我什么都写不了。它仍然是空的。

我该怎么解决这个问题?

下面是我的代码(grv-gridview,ds数据集):

        grv1.AutoGenerateColumns = false;
        grv1.DataSource = ds.Tables[0];        
        grv1.Columns[0].DataPropertyName = "LastName";

        DataGridViewTextBoxColumn nrCol = new DataGridViewTextBoxColumn();
        nrCol.Name = "Nr";
        nrCol.HeaderText = "Nr";
        grv.Columns.Insert(0, nrCol);
        grv.Columns[0].ReadOnly = false;

        for (int i=0;i<grv.Rows.Count;i++)
        {
            grv.Rows[i].Cells[0].Value = i.ToString();       
        }

我可以';t更改Gridview中的列值

您的网格中有行吗?我看到了添加列的代码,以及为当前每一行更改字段的循环,但我没有看到添加行的代码。

您需要在循环中使用预先填充的DataGridViewRow来调用grv.Rows.Add(...)

我认为在绑定数据源之后,您需要find the controlassign the value to the Text property of TextBox control(而不是到单元格);单元格值可能不可见,因为TextBox正在覆盖它…

//your code here
...
//assign data source (if you have any)
grv.DataSource = YourDataSource;
//bind the gridview
grv.DataBind();
//now you can loop through the gridview as below
for (int i=0;i<grv.Rows.Count;i++)
{
    TextBox txt = (TextBox)grv.Rows[i].FindControl("Nr");
    txt.Text = i.ToString();
}

或者您可以按照以下方式巧妙地执行此操作;

代码隐藏:

//define index variable in the code behind
protected int index = 1;

HTML:

<!--Add this column to the GridView with your text box -->
<asp:TemplateField>
   <ItemTemplate>
       <asp:TextBox runat="server" ID="Nr" text='<%# index ++ %>'></asp:TextBox>
   </ItemTemplate>
</asp:TemplateField>

如果我是正确的,那么您有Person表或类似的东西。您不需要以这种方式为该表创建autonumber,只需从数据库中设置该表的primary keyauto-increment = true即可。

更新

只要看看你的评论,这就是解决你问题的好办法。ROW_NUMBER。

谢谢大家,我自己解决了这个问题,有点脏。

这个行号很方便,我把它添加到我的技巧中;)

但这次我所做的是将我创建的数据网格collmn绑定到数据集中的一些随机collmn。当它未绑定时,我什么都写不出来。当它被绑定时,我很容易地覆盖的值

    grv1.AutoGenerateColumns = false;
    grv1.DataSource = ds.Tables[0];        
    grv1.Columns[0].DataPropertyName = "LastName";

    DataGridViewTextBoxColumn nrCol = new DataGridViewTextBoxColumn();
    nrCol.Name = "Nr";
    nrCol.HeaderText = "Nr";
    grv1.Columns.Insert(0, nrCol);
    grv1.Columns[0].ReadOnly = false;
    //!!!!!!!!!!!!!!!!!!!!!!
    grv1.Columns[0].DataPropertyName = "Postal code"; //or whatever existing column 

    for (int i=0;i<grv.Rows.Count;i++)
    {
        grv.Rows[i].Cells[0].Value = i.ToString();       
    }