Search code examples
c#sqlasp.nethyperlinksql-search

Create links from String results after SQL search


I have successfuly searched my DB table for what i want and passed it into a DataTable (dt). The idea is that i want (after the search) to redirect someone to the result page he likes.

So if he Searches for example "Michael" , i'd like to show him , the name Michael as a link , and if he presses it redirect him to his page, which is made by ~/Default.aspx?Email="+ id (id also results after the search and is casted to string).

My Code:

protected void Button1_Click1(object sender, EventArgs e)
        {

            DataTable PassRecord = new DataTable();


            String str = "select First_Name,Surname,id from ID where (First_Name like '%'+ @search +'%' ) OR (Surname like '%'+ @search +'%') OR (Email_Account like '%'+ @search +'%')";


            SqlCommand Srch = new SqlCommand(str, con);
            Srch.Parameters.Add("@search", SqlDbType.NVarChar).Value = TextBox1.Text;



            con.Open();
            Srch.ExecuteNonQuery();
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = Srch;


            DataTable dt = new DataTable();
            DataSet ds = new DataSet();
            da.Fill(dt);



            foreach (DataRow dr in dt.Rows)
            {


                var field = dr["First_Name"].ToString();
                Response.Write(field);
                Response.Write("<br/>");
            }

As u understand i want to create a link redirecting to the users profile after the search.

Any help is appreciated, Thanks in Advance !!!

Michael.


Solution

  • I personally prefer using

    var field = "<a href='" + Page.ResolveUrl("~/Default.aspx?Email=" + dr["id"]) + "'>" + (dr["First_Name"] + "").ToString() + "</a>";
    

    It's mainly as @Mikhail Timofeev said but with tiny modification.

    Explanation :

    Page.ResolveUrl: ensure to refers relatively to where user is at in your website's tree so it can be use by client (Browser) (See Source).

    dr["First_Name"] + "" is prefered, for me, in case a DBNull.Value may comes here and may fails if it happens.