我无法更改GridView中的列值
问题描述:
我试图将自动编号列插入到C#中的datagridview控件中。我无法更改GridView中的列值
一切正常,但我不能写任何东西到列。它仍然是空的。
我该如何解决这个问题?
下面是我的代码(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();
}
答
你有你的网格行?我看到添加了一列的代码,以及为每个当前行更改字段的循环,但我看不到添加行的代码。
您需要拨打grv.Rows.Add(...)
并在循环中预先填写DataGridViewRow
。
答
我认为你需要find the control
和assign the value to the Text property of TextBox control
(不细胞)绑定数据源后;单元格的值可能是不可见的,因为文本框是覆盖它...
//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 key
和auto-increment = true
并完成。
UPDATE
刚刚看了你的评论,这是你的问题很好的解决方案。 ROW_NUMBER。
答
感谢人们,我自己用一种肮脏的方式解决了这个问题。
这ROWNUMBER是很方便的,我把它添加到我的招数;)
但我所做的这段时间内我创建的DataGrid collumn结合,从数据集中一些随机collumn。当它被解约时,我什么都不能写。当它被结合我容易改写的值
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();
}
是的,我的行,这是从数据集中读取:grv1.DataSource = ds.Tables [0]; – RRM 2013-02-13 09:59:50
然后我建议你更新你的代码示例以匹配你使用的实际代码。 – 2013-02-13 10:35:24