Change sqldatasource select command at runtime

Html

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="SqlDataSource1">
   <Columns>
       <asp:BoundField DataField="id" HeaderText="id"  />
       <asp:BoundField DataField="name" HeaderText="name" />
   </Columns>
 </asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:database1ConnectionString %>"
SelectCommand="SELECT * from tblCourse"></asp:SqlDataSource>

      

code

 SqlDataSource1.SelectCommand =
        "SELECT  * from tblCourse where name='"+textbox1.text+"'";
  SqlDataSource1.DataBind();

      

But the Gridview doesn't change depending on the new select command, even when I use DataBind ()

How can we change the basic grid structure to sql data source selection command?

+3


source to share


5 answers


This is due to the GridView

viewstate.

When the postback occurs, the gridview stores its data from the ViewState. This way you can disable the view state for the GridView (good practice?) OR you call GridView.DataBind()

in addition toSqlDataSource.Databind();

METHOD 1 : challengeGridView.DataBind();

protected void Page_Load(object sender, EventArgs e)
 {
     if (this.IsPostBack)
     {
        string command = SqlDataSource1.SelectCommand; // added just for debug purpose
        SqlDataSource1.SelectCommand = "SELECT  * from tblCourse where 
                                        name='"+textbox1.text+"'";
        SqlDataSource1.DataBind();
        gridview1.DataBind();
      }

  }

      

METHOD 2 : Disable View State for GridView ( Is this good practice? ). When you install this false

, there is no need to call GridView.DataBind()

in yours page_Load

as shown in METHOD 1 above.



<asp:GridView runat="server" ID="gridview1" EnableViewState="false" ...  />

      

Now comes the part to take care of:

Make sure that, <asp:BoundField>

or in general, any fields declared and bound to the markup GridView

are also present in your new request, otherwise an error will be thrown saying something like this:

A field or property with the name 'ID' was not found on the selected data source

      

+2


source


You can edit your BoundField or change the property AutoGenerateColumns

to true

.



0


source


string strSql= "SELECT  * from tblCourse where name='abc'";
ViewState["SQL"]=strSql;
SqlDataSource1.SelectCommand =strSql;        
SqlDataSource1.DataBind();

      

Now in Page_Load

if(IsPostback)
     SqlDataSource1.SelectCommand=ViewState["SQL"].ToString();

      

0


source


Set autogenerate to true and be sure to delete all fields in the edit field wizard. If you change the select command, it will cause a conflict.

0


source


Try adding the following:

 SqlDataSource.select(DataSourceSelectArguments.Empty);

      

in front of the line SqlDataSource.DataBind();

0


source







All Articles