如何使用动态数据绑定在AspxGridView中显示记录?

时间:2016-12-19 09:57:06

标签: c# asp.net data-binding devexpress aspxgridview

我想用AspxGridView做动态数据绑定。如果我设置AutoGenerateColumn = true它显示所选列的列名但不显示记录。如果我将false设置为自动生成列,则页码数会增加,但记录不会显示。

Asp.net代码

<dx:ASPxGridView ID="ASPxGridView1" runat="server">
    <SettingsPager PageSize="50">
    </SettingsPager>
    <Settings ShowFilterRow="True" ShowGroupPanel="True" />
    <SettingsCommandButton>
        <ShowAdaptiveDetailButton ButtonType="Image"></ShowAdaptiveDetailButton>
        <HideAdaptiveDetailButton ButtonType="Image"></HideAdaptiveDetailButton>
    </SettingsCommandButton>
    <SettingsDataSecurity AllowDelete="False" AllowEdit="False" AllowInsert="False" />
    <SettingsSearchPanel Visible="True" />
</dx:ASPxGridView>

cs文件

protected void btnSearch_Click(object sender, EventArgs e)
{
    string cs = ConfigurationManager.ConnectionStrings["HQMatajerConnectionString"].ConnectionString;

    using (SqlConnection con = new SqlConnection(cs))
    {
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "select * from [HQMatajer].[dbo].[TransactionEntry] where itemid='74876'";
        con.Open();
        SqlDataReader rd = cmd.ExecuteReader();

        //ASPxGridView1.Columns.Clear();
        ASPxGridView1.AutoGenerateColumns = true;
        ASPxGridView1.DataSource = rd;
        ASPxGridView1.DataBind();
    }
}

输出

If AutoGenerateColumns = true

如果我设置为false,则输出以下图像 Output 2 if I set AutoGenerateColumns = false

1 个答案:

答案 0 :(得分:0)

SqlDataReader是快速获取记录的一个很好的解决方案,但是你不能按原样使用它来填充GridView对象的DataSource。您应该将它与DataSet或DataTable结合使用以实现您的目标。 这两个类都有Load属性,以便从SQLDataReader对象中获取结果。

SqlDataReader rd = cmd.ExecuteReader();
DataTable dt= new DataTable();
dt.Load(rd);
ASPxGridView1.DataSource = dt;

另请查看https://msdn.microsoft.com/en-us/library/system.data.datatable.load(v=vs.110).aspx