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?
source to share
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
source to share