Arama yaptıracağımız sayfaya bir textbox ve bir buton ekleyelim
Default.aspx
<asp:TextBox ID="txtArama" runat="server"></asp:TextBox>
<asp:Button ID="btnAra" runat="server" OnClick="btnAra_Click" Text="Ara" />
Butona çift tıklayalım ve aşağıdaki kodları yazalım
Default.aspx.cs
protected void btnAra_Click(object sender, EventArgs e)
{
string aranan = SqlInjectionTemizle(txtArama.Text);
if (aranan.Length < 3)
{
ClientScript.RegisterStartupScript(typeof(Page), "asd", "<script>alert('Arama için en az üç harf girmelisiniz');</script>");
}
else
{
Response.Redirect("Arama.aspx?ara=" + aranan + "");
}
}
public string SqlInjectionTemizle(string text)
{
text = text.Replace(">", "");
text = text.Replace("<", "");
text = text.Replace("--", "");
text = text.Replace("'", "");
text = text.Replace("char ", "");
text = text.Replace("delete ", "");
text = text.Replace("insert ", "");
text = text.Replace("update ", "");
text = text.Replace("select ", "");
text = text.Replace("truncate ", "");
text = text.Replace("union ", "");
text = text.Replace("script ", "");
return text;
}
Örnek olarak bir haber sitemiz olduğunu düşünelim ve haberler tablomuzdaki baslik ve detay alanlarında arama yaptıralım. Arama.aspx sayfamıza bir gridview ekleyelim ve kod tarafına aşağıdaki kodları yazalım
Arama.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
public partial class Arama : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["ara"] != null)
{
string aranan = Request.QueryString["ara"];
HaberleriGetir(aranan);
}
}
private void HaberleriGetir(string aranan)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString);
SqlDataAdapter adp = new SqlDataAdapter("Select haberID,baslik,detay From haberler Where baslik Like '%" + aranan + "%' OR detay LIKE '%" + aranan + "%' Order By haberID Desc",conn);
DataTable tbl = new DataTable();
adp.Fill(tbl);
GridView1.DataSource = tbl;
GridView1.DataBind();
}
}