从gridview中手动删除一行?

时间:2013-12-03 15:02:18

标签: asp.net sql vb.net gridview

我有一个gridview,它绑定到一个允许下载文件的表。该表包括:

  • tableid as int
  • filename as string
  • filepath as string
  • 删除(在gridview中添加了列)

此删除不是自动的,它是编码的。我希望用户单击删除,所选行将被删除。很简单,但我似乎无法获取要删除的行的ID。这就是我所做的:

  Try
        'Get the Image_Id from the DataKeyNames
        Dim imgId As Integer = Convert.ToInt32(gvDetails.DataKeys(e.RowIndex).Value)


        Dim cmd As New SqlCommand("delete from FilesTable where id=@id", con)
        cmd.Parameters.AddWithValue("@id", imgId)
        cmd.CommandType = CommandType.Text
        con.Open()
        cmd.ExecuteNonQuery()
    Catch ex As Exception
        ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occured : " & ex.Message.ToString() & "');", True)
    End Try

但是我一直收到错误,即字符串输出无法转换为Integer:

  

发生错误:输入字符串的格式不正确。

请帮助!

这是网格视图的绑定方式:

Private Sub BindGridviewData() 
    Try 
        con.Open() 
        Dim cmd As New SqlCommand("select * from FilesTable", con) 
        Dim da As New SqlDataAdapter(cmd) 
        Dim ds As New DataSet() 
        da.Fill(ds) 
        con.Close() 
        gvDetails.DataSource = ds 
        gvDetails.DataBind() 

    Catch ex As Exception 
        Response.Write(ex.Message) 
    End Try 
End Sub

1 个答案:

答案 0 :(得分:0)

经过很长一段时间我找到了答案,这是一个简单的问题:

而不是: Dim imgId As Integer = Convert.ToInt32(gvDetails.DataKeys(e.RowIndex).Value)

我将其改为:

Dim imgId As Integer = Int32.Parse(gvDetails.Rows(e.RowIndex).Cells(0).Text)