帮助从存储过程中填充gridview

时间:2010-12-30 19:03:39

标签: asp.net vb.net ado.net

我正在尝试执行存储过程并将信息放在数据网格中(不使用.net向导)我想手动执行此操作。使用ado.net我相信。我正在使用vb.net和asp.net

 Public cmd As New SqlCommand()
    Public saoda As New SqlDataAdapter(cmd)
    Public conn As New SqlConnection("    ")
    Dim saods As New DataSet

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim reader As SqlDataReader
        cmd.Parameters.AddWithValue("@yeartoget", DropDownList1.SelectedValue)
        cmd.CommandText = "casof"
        cmd.CommandType = CommandType.StoredProcedure
        cmd.Connection = conn

        conn.Open()

        reader = cmd.ExecuteReader()
        ' Data is accessible through the DataReader object here.

        GridView1.DataSource = saods

        saoda.FillSchema(saods, SchemaType.Mapped)

        GridView1.DataBind()
        conn.Close()

    End Sub
End Class

vvvvv

Dim pctofsales As New DataColumn
        pctofsales = New DataColumn("PCTofsales", GetType(Decimal))
        pctofsales.Expression = "IIF([YEsales] = 0, 0, [ASOFSales] / [YEsales])"
        saods1.Tables("salesasoftable").Columns.Add(pctofsales)

1 个答案:

答案 0 :(得分:1)

您不需要将DataSet绑定到GridView - SqlDataReader就足够了。也就是说,您可以使用以下内容:

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim reader As SqlDataReader
    cmd.Parameters.AddWithValue("@yeartoget", DropDownList1.SelectedValue)
    cmd.CommandText = "casof"
    cmd.CommandType = CommandType.StoredProcedure
    cmd.Connection = conn

    conn.Open()

    reader = cmd.ExecuteReader()

    GridView1.DataSource = reader
    GridView1.DataBind()

    conn.Close()
End Sub

但是,如果你想/需要使用DataTable,那也没什么大不了的。以下代码段将阅读器加载到DataTable中:

Dim reader As SqlDataReader
cmd.Parameters.AddWithValue("@yeartoget", DropDownList1.SelectedValue)
cmd.CommandText = "casof"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = conn

conn.Open()

reader = cmd.ExecuteReader()

Dim myTable As DataTable = New DataTable()
myTable.Load(reader)

GridView1.DataSource = dt
GridView1.DataBind()

conn.Close()

快乐编程!