How to show records in AspxGridView using dynamic databind?

1.6k views Asked by At

I want to do dynamic databind with AspxGridView. If I set AutoGenerateColumn = true It's showing column name of selected columns but not records. If I set false to auto generate column, the number of page number increases but records are not displaying.

Asp.net code

<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 file

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

output

If AutoGenerateColumns = true.

If i set false the following image is the output Output 2 if I set AutoGenerateColumns = false

1

There are 1 answers

0
jambonick On

SqlDataReader is a good solution for fast fetching records but you don't use it as is in order to fill in the DataSource of a GridView object. You should use it in combination with DataSet or DataTable to achieve your goal. Both classes have Load property in order to get results from a SQLDataReader object.

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

Also check this out https://msdn.microsoft.com/en-us/library/system.data.datatable.load(v=vs.110).aspx