Click here to Skip to main content
15,893,337 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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
XML
<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",connect.cn());
            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);
            da.Fill(dt);
            SqlDataSource1.SelectCommand = dt;
            SqlDataSource1.DataBind();


But it is display Error how do it please help me
Posted

1 solution

Hi,
Try this:

C#
SqlDataSource1.DataSourceMode=SqlDataSourceMode.DataReader;
SqlDataSource1.SelectCommand = "select * from table1 where name='"+txtName.Text+"'";
SqlDataSource1.ConnectionString = ConfigurationManager.ConnectionStrings["MyConString"].ConnectionString;

//Now rebind the grid;
GridView2.DataSource = SqlDataSource1;
GridView2.DataBind();

// 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.



--Amit
 
Share this answer
 
v4
Comments
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.
Member 15570764 6-Feb-23 6:50am    
v
_Amy 1-Aug-12 2:32am    
Try my updated answer.
Member 15570764 6-Feb-23 6:50am    
v
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

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900