实现:Datagrid显示数据库的信息,最后一个字段是TextBox模板列,页面有一个保存按钮。当修改了多条记录的Textbox的值后,点保存,想逐条判断Datagrid,更新数据库,但是提示什么索引值超出范围。希望大侠们解决。
代码:Private Sub BindGrid()
        Dim c1 As New BoundColumn
        c1.HeaderText = "ID"
        c1.DataField = "CaseID"
        DataGrid1.Columns.AddAt(0, c1)
        Dim c2 As New BoundColumn
        c2.DataField = "CaseName"
        c2.HeaderText = "Name"
        DataGrid1.Columns.AddAt(1, c2)
        Dim tm As New TemplateColumn
        tm.ItemTemplate = New ColumnTemplate2("Quantity") '
        tm.HeaderText = "数量"
        DataGrid1.Columns.AddAt(2, tm) '
        SetBind()
    End Sub
     Public Sub SetBind()        '数据库连接对象
        Dim cnSqlServer As New SqlConnection(Session("strConnection"))
        '打开数据库
        cnSqlServer.Open()
        Dim strSQL As String        '数据库查询语句        Dim myCommand As SqlDataAdapter         '定义数据库命令对象
        Dim ds As DataSet = New DataSet         '查询结果集
        strSQL = "Select CaseID,CaseName,Quantity From vwCaseInfo"
        myCommand = New SqlDataAdapter(strSQL, cnSqlServer)       '执行查询命令        myCommand.Fill(ds)          '执行结果填充到DataSet        DataGrid1.DataSource = ds.Tables(0)
        DataGrid1.DataKeyField = "CaseID"
        DataGrid1.DataBind()
    End Sub    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        '在此处放置初始化页的用户代码
        If Not IsPostBack Then            BindGrid()
        End If
    End Sub    Private Sub Btn_Save_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Btn_Save.Click        Dim a As Integer
        
        a = Val(DataGrid1.Items(0).Cells(2).Text)
    End Sub保存按钮里,执行到a时出错。

解决方案 »

  1.   

    datagrid不是有绑定列么?怎么你还这样,而且你动态添加列,提交的时候能取得到么?
      

  2.   

    DataGrid1.Items(0).Cells(2).Text 是老的数据,原来是空应该。取当前的值应该这样写
    TextBox tLnkTxt = (TextBox)e.Item.Cells[1].Controls[0];
    string LnkTxt = tLnkTxt.Text;
    可惜我只会c#,你自己改成vb吧
      

  3.   

    不要用 Cells[1].Controls[0] 这样的方式,因为你怎么知道这个控件就是你要的控件呢?
      

  4.   

    现在是如果Datagrid自动创建列,这样取也能取到,就是加了个模板列,就不行了。
      

  5.   

    晕 楼主,我对你说的你怎么都不听噢
    叫你不要用 Cells[1].Controls[0] 这样的访问方式!
    为什么呢? 因为你怎么知道你要访问的控件就是Cells[1].Controls[0]? 
    (你试一试Cells[1].Controls[1])特别是你对DataGrid没有熟练掌握的情况之下 更不要用这样的方法
    而且这样的程序可读性差。那应该怎么办呢? 换一种方法。 比如,你用来新增的记录的输入框,有好几个,
    那么我们假设其中一个为: txtUserName (类型为:TextBox)
    访问方法如下:
    C#:
      DataGridItem tempGridItem;
      tempGridItem = DataGrid1.Items[0];
      TextBox  UserNameBox;
      UserNameBox =  (TextBox)tempGridItem.FindControl("txtUserName");
      Response.Write(UserNameBox.Text);