2013-02-12 37 views
2

我试图将自动编号列插入到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();  
     } 

回答

2

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

您需要拨打grv.Rows.Add(...)并在循环中预先填写DataGridViewRow

+0

是的,我的行,这是从数据集中读取:grv1.DataSource = ds.Tables [0]; – RRM 2013-02-13 09:59:50

+0

然后我建议你更新你的代码示例以匹配你使用的实际代码。 – 2013-02-13 10:35:24

1

我认为你需要find the controlassign 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> 
+0

对不起,我忘了说它是桌面应用程序,而不是ASP.NET。我没有可用的DataBind或FindControl等方法 – RRM 2013-02-13 09:58:31

+0

在这种情况下,您应该在添加列和循环前分配数据源。 – Kaf 2013-02-13 10:07:34

0

如果我是正确的,你有Person表或类似的东西。您不需要为该表创建autonumber,只需从数据库中设置该表的primary keyauto-increment = true并完成。

UPDATE

刚刚看了你的评论,这是你的问题很好的解决方案。 ROW_NUMBER

+0

这是真的,但我在SQL服务器上使用我的表中的一些记录选择并按名称排序。如果我使用表键我会有像5467,3412,7896等数字,我想它是1,2,3 – RRM 2013-02-13 10:05:06

+0

我更新了我的答案 – spajce 2013-02-13 10:09:59

0

感谢人们,我自己用一种肮脏的方式解决了这个问题。

这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();  
    }