Search code examples
c#asp.netsql-serverdynamic-data

Dynamic input to sql query Using asp.net


I have a hyperlink which should print information from sql database.But I'm not able to know how to give that hyperlink value to sql query.

SqlConnection conn = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
        SqlDataAdapter ADP = new SqlDataAdapter("select * from News where Headlines= au_id", conn);

I want to get value au_id dynamically can anybody help me with this after clicking on the hyperlink.

Its like when i click on the headlines i should get the corresponding news.


Solution

  • First of all, you should use a LinkButton instead of a Hyperlink control as hyperlink redirects the page to a specified URL. But the LinkButton has a Click Event handler. On that click you can get the ID.

    Your query will be look like...

    SqlDataAdapter ADP = new SqlDataAdapter("select * from News where Headlines = " + au_id, conn);
    

    But It would be better if you use a Parameterized query to save yourself from a SQL Injection Attack.

    SqlDataAdapter ADP = new SqlDataAdapter("select * from News where Headlines = @au_id", conn);
    ADP.SelectCommand.Parameters.Add("@au_id", System.Data.SqlDbType.Int, 4, "au_id");