0

I have a GridView combine with data from SQL Server.

I want the GridView to show all the Movies and customers names and last names, by choosing the first letter of the movie only. The user will input the first letter in the TextBox.

I think <asp:ControlParameter can be used here but I don't know how.

Here its design:

enter image description here

Searching the forum, I found something like this solution, but it gave me an error - System.NullReferenceException:

    protected void Button1_Click(object sender, EventArgs e)
{
    if (!String.IsNullOrEmpty(TextBox1.Text))
    {
        (GridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("FirstName LIKE '{0}%'", TextBox1.Text);
    }
}

enter image description here

Will be glad for some clues,

Thank you in advance!

7
  • The exception means that one of the objects your are manipulating is null. Have you checked which object is causing this exception by debugging step by step ? Commented Sep 16, 2020 at 14:37
  • @MarleneHE I tried, but I cant figure it out. it jump stright to the line above. Commented Sep 16, 2020 at 14:51
  • 1
    My guess would be that since you use an SqlDataSource on the aspx page, GridView1.DataSource as DataTable is null since that code is executed before data is bound to the GridView. Commented Sep 16, 2020 at 16:30
  • @VDWWD OK thanks, any idea how to do what I'm searching? Commented Sep 16, 2020 at 16:45
  • 1
    Being that the button click does a postback, you may want to have the datasource in a session variable (and update it on every postback). I'm thinking the datasource is null and its throwing the error because of it. Commented Sep 16, 2020 at 17:41

1 Answer 1

0

I found the solution - how to use <asp:ControlParameter :

<asp:SqlDataSource ID="SqlDataSource_Movie" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString2 %>" SelectCommand="(long generated code, than)--> WHERE (MovieName LIKE @Text + '%') ORDER BY FirstName ASC">
        <SelectParameters>    <asp:ControlParameter  ControlID="TextBox1" Name="Text"/>   </SelectParameters>
        </asp:SqlDataSource>

Now I can input the first letter of the Movie and it will filter the GridView to show all the users that rent movies which starts with this letter.

Thanks

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.