Click here to Skip to main content
13,095,658 members (52,053 online)
Rate this:
Please Sign up or sign in to vote.
See more:
I am using Sqldatasource for Gridview. I want to change the datasource at runtime how to do it please help me.
I give the following command at design page
<asp:GridView ID="GridView2" OnRowDataBound="GridView2_RowDataBound" DataSourceID="SqlDataSource1" runat="server" align="center" AutoGenerateColumns="False"
       BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px"
       CellPadding="3"  GridLines="Vertical" Height="161px" Width="837px">
       <RowStyle BackColor="#EEEEEE" ForeColor="Black" />

And I want to Change the datasource select command for below code
SqlCommand sqlcmd = new SqlCommand("FETCH_COUNTER_UMAP_SP",;
            sqlcmd.Parameters.AddWithValue("@COMPANYCODE", company_name);
            sqlcmd.Parameters.AddWithValue("@BRANCHCODE", s);
            sqlcmd.Parameters.AddWithValue("@USERID", uname);
            sqlcmd.Parameters.AddWithValue("@FINYEAR", Finyear);
            sqlcmd.Parameters.AddWithValue("@ERRORID", 1);
            sqlcmd.Parameters.AddWithValue("@MAPUSERID", cmbusers.SelectedValue);
            sqlcmd.CommandType = CommandType.StoredProcedure;
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(sqlcmd);
            SqlDataSource1.SelectCommand = dt;

But it is display Error how do it please help me
Posted 31-Jul-12 19:59pm

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Try this:

SqlDataSource1.SelectCommand = "select * from table1 where name='"+txtName.Text+"'";
SqlDataSource1.ConnectionString = ConfigurationManager.ConnectionStrings["MyConString"].ConnectionString;
//Now rebind the grid;
GridView2.DataSource = SqlDataSource1;
// Changing sqldatasouce to datatable
//create dataview from sql data source 
DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
//convert dataview to datatable
DataTable dt = dv.ToTable();
//Now dt is the table with all the values.

devausha 1-Aug-12 2:14am
Thank you for your reply. If I used datatable or datareader like in questions, How I assign it? Please help me.
_Amy 1-Aug-12 2:32am
Try my updated answer.
devausha 1-Aug-12 2:58am
Thank you for your reply. I want how to set the datasource of the Sqldatasource1 to dt or ds
_Amy 1-Aug-12 3:27am
Commands are required for that. Use commands. Try reading this:[^]
devausha 1-Aug-12 5:09am
Thank you this link is very useful
_Amy 1-Aug-12 5:47am
Welcome. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web01 | 2.8.170813.1 | Last Updated 1 Aug 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100