Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I currently have this code to populate ASP.NET gridview from code behind with DataTable.

 protected void bindGridView()
    {
        SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["connstr"].ConnectionString);
        SqlCommand cmd = sqlConn.CreateCommand();
        cmd.CommandText = "SELECT id AS 'Member ID', name AS Name, age AS Age, sympton AS Sympton, phone AS Phone, nirc AS NIRC, address AS Address FROM tbl_customer_profile WHERE id = @id";
        cmd.Parameters.AddWithValue("@id", txtSearchID.Text);
        DataTable dtSearchResult = new DataTable();
        SqlDataAdapter daSearchResult = new SqlDataAdapter();

        try
        {
            sqlConn.Open();
            daSearchResult.SelectCommand = cmd;
            daSearchResult.Fill(dtSearchResult);
            gridSearchResult.DataSource = dtSearchResult;
            gridSearchResult.DataBind();
        }
        catch (SqlException ex)
        {
            lblStatus.Text = ex.Message;
        }
        finally
        {
            sqlConn.Close();
        }
    }

But I would lose the Grid's Selection, Sorting, Paging functions. So I was thinking if I could fill to SqlDataSource instead of Datatable and then bind to Gridview, I wouldn't have to handle the selection, sorting etc manually?

But I can't just simply do like daSearchResult.Fill(sqlDataSource1);

Is there any workaround?

share|improve this question

1 Answer 1

Kind of like what Neeraj was saying you can bind directly to a gridview with an SqlDataSource. You don't need to have all that plumbing code.

This is how in asp.net

      <asp:GridView ID="grid" runat="server" DataSourceID="source"></asp:GridView>
      <asp:SqlDataSource ID="source" runat="server"></asp:SqlDataSource>

This is how in C#

        SqlDataSource source =new SqlDataSource();
        GridView grid = new GridView();

        grid.DataSource = s;
        grid.DataBind();
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.