how can i search a string in sql database table - c#

this is my program
public partial class message : System.Web.UI.Page
{
string constring = ConfigurationManager.ConnectionStrings["AnonymiousSocialNetworkConnectionString"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
txtuseremil.Text = Session["emid"].ToString();
}
protected void btnsend_Click(object sender, ImageClickEventArgs e)
{
SqlConnection con = new SqlConnection(constring);
string value = txtmsg.Text;
if (value.Contains(SqlCommand cmd = new SqlCommand("select keyword from messageanalysis where keyword=#value"))// <--MY PROBLEM
{
con.Open();
lblStatus.Text = "Normal"; <-- I WANT TO DERIVE THIS VALUE FROM TABLE ACCORDING TO THE VALUE I GET FROM keyword
Frdsclass.Text = "Just Friend"; <--- I WANT TO DERIVE THIS VALUE FROM TABLE ACCORDING TO THE VALUE I GET FROM keyword
SqlCommand cmd = new SqlCommand("insert into messagetable(sendid,message,userid,emotional,friendsclassify) values (#snd,#msg,#usr,#emo,#frdcl)", con);
cmd.Parameters.AddWithValue("#snd", txtsndmail.Text);
cmd.Parameters.AddWithValue("#msg", txtmsg.Text);
cmd.Parameters.AddWithValue("#usr", txtuseremil.Text);
cmd.Parameters.AddWithValue("#emo", lblStatus.Text);
cmd.Parameters.AddWithValue("#frdcl", Frdsclass.Text);
cmd.ExecuteNonQuery();
con.Close();
}
how can i search a word or sentence in database table?? is my method correct?? plz help if u have a solution

your question is not quite clear. If you want to search a substring in a varchar field you can do it with a like
SELECT * FROM yourtable WHERE yourvarcharfield LIKE '%yoursearchstring%'
if you wanto look in different fields you can chain with ...or yourotherFild like '%yousearchstring%'
if you want to search those records that start with your searchstring the condition is
..like 'yoursearchstring%'

public string GetValue (string searchValue)
{
using(SqlConnection connection = new SqlConnection(connString));
using(SqlCommand cmd = new SqlCommand(
"select keyword from messageanalysis where value=#value")
{
cmd.AddParameter("#value",searchValue);
var result = cmd.ExecuteScalar();
return (result == null)? null : result.ToString();
}
}
....
var keyword = GetValue(value);
if (keyword != null && value.Contains(keyword)){
....
You could do something like this. I've separated your select statement into a different function. This will look for your value that you pass in and return your keyword. if it doesn't find it, the function returns null. I then set it to check and see if the keyword is null (since null is not found) and if it finds the value to execute the conditional code.

Try this...
NOTE:ExecuteScalar() will returns the first record of the resultset.
public partial class message : System.Web.UI.Page
{
string constring = ConfigurationManager.ConnectionStrings["AnonymiousSocialNetworkConnectionString"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
txtuseremil.Text = Session["emid"].ToString();
}
protected void btnsend_Click(object sender, ImageClickEventArgs e)
{
SqlConnection con = new SqlConnection(constring);
string value = txtmsg.Text;
SqlCommand cmd = new SqlCommand("select keyword from messageanalysis where keyword = #value")
cmd.Parameters.AddWithValue("#value", Keywordtextbox.text);
cmd.Connection=con;
con.Open();
if (Keywordtextbox.text.Contains(cmd.ExecuteScalar()))
{
lblStatus.Text = "Normal";
Frdsclass.Text = "Just Friend";
SqlCommand cmd = new SqlCommand("insert into messagetable(sendid,message,userid,emotional,friendsclassify) values (#snd,#msg,#usr,#emo,#frdcl)", con);
cmd.Parameters.AddWithValue("#snd", txtsndmail.Text);
cmd.Parameters.AddWithValue("#msg", txtmsg.Text);
cmd.Parameters.AddWithValue("#usr", txtuseremil.Text);
cmd.Parameters.AddWithValue("#emo", lblStatus.Text);
cmd.Parameters.AddWithValue("#frdcl", Frdsclass.Text);
cmd.ExecuteNonQuery();
con.Close();
}

if your textfield can contain more than one word you have to separate the words in the appropriate number of strings and then
select the records with a like saerch as shown in my previous answer
SELECT * FROM yourtable WHERE yourvarcharfield LIKE '%string1%' or yourvarcharfield LIKE '%string2%' or ...
as the textfield can have various numbers of words you have to build your sqlcommand with a stringbuilder.

Related

Using SAME Textbox to search and insert data in dataGridView

I have a Textbox with which I want to be able to Search and Insert data into Table. Insert works fine with one exception: When I try to Insert data that isn't already in DB(it's searching while I'm typing) it gives me:
"Exception User-Unhandled System.NullReferenceException: 'Object
reference not set to an instance of an object.'
System.Windows.Forms.DataGridView.CurrentRow.get returned null.
I think I'm missing something in the Search code.
//UPDATE: All of the code.// This is my Insert and Search code:
namespace UDDKT
{
public partial class FrmGlavna : Form
{
DataSet ds = new DataSet();
SqlDataAdapter DaDavaoci = new SqlDataAdapter();
SqlDataAdapter DaAkcije = new SqlDataAdapter();
SqlConnection cs = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\UDDKT.mdf;Integrated Security=True");
public FrmGlavna()
{
InitializeComponent();
}
//Popunjava DataGridViews sa podacima iz baze
private void FrmGlavna_Load(object sender, EventArgs e)
{
SqlCommand SlctDavaoci = new SqlCommand("SELECT * FROM Davaoci ORDER BY DavaocID DESC", cs);
DaDavaoci.SelectCommand = SlctDavaoci;
DaDavaoci.Fill(ds, "TblDavaoci");
SqlCommand SlctAkcije = new SqlCommand("SELECT * FROM AkcijaDDK", cs);
DaAkcije.SelectCommand = SlctAkcije;
DaAkcije.Fill(ds, "TblAkcije");
DgDavaoci.DataSource = ds.Tables["TblDavaoci"];
}
//Povezuje DataGridViews Davaoca i Akcija
private void DgDavaoci_SelectionChanged(object sender, EventArgs e)
{
ds.Tables["TblAkcije"].DefaultView.RowFilter = "DavaocID =" + DgDavaoci.CurrentRow.Cells["DavaocID"].Value;
DgAkcije.DataSource = ds.Tables["TblAkcije"];
}
//Osvježava DataGridView nakon unosa/izmjene/brisanja podataka u bazu
private void RefreshTable()
{
SqlConnection cs = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\UDDKT.mdf;Integrated Security=True");
String query = "SELECT * FROM Davaoci ORDER BY DavaocID DESC";
SqlCommand cmd = new SqlCommand(query, cs);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
DgDavaoci.DataSource = dt;
}
//Čisti TextBox nakon upisa/izmjene/brisanja podataka u bazu
public void ClearTxtBx()
{
TxtIme.Clear();
TxtPrezime.Clear();
TxtTezina.Clear();
TxtAdresa.Clear();
TxtBrojTel.Clear();
TxtBrojLK.Clear();
}
//Upis podataka u Tabelu Davaoci
private void BtnDodajDavaoca_Click(object sender, EventArgs e)
{
String query = "INSERT INTO Davaoci (Ime,Prezime,Pol,DatumRodjenja,KrvnaGrupa,Tezina,Adresa,BrojTel,BrojLK) VALUES (#Ime, #Prezime, #Pol, #DatumRodjenja, #KrvnaGrupa, #Tezina, #Adresa, #BrojTel, #BrojLK)";
using (SqlConnection cs = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\UDDKT.mdf;Integrated Security=True"))
using (SqlCommand command = new SqlCommand(query, cs))
{
command.Parameters.Add("#Ime", SqlDbType.NVarChar).Value = TxtIme.Text;
command.Parameters.Add("#Prezime", SqlDbType.NVarChar).Value = TxtPrezime.Text;
command.Parameters.Add("#Pol", SqlDbType.NChar).Value = TxtPol.Text;
command.Parameters.Add("#DatumRodjenja", SqlDbType.Date).Value = TxtDatumRodjenja.Text;
command.Parameters.Add("#KrvnaGrupa", SqlDbType.VarChar).Value = TxtKrvnaGrupa.Text;
command.Parameters.Add("#Tezina", SqlDbType.Float).Value = TxtTezina.Text;
command.Parameters.Add("#Adresa", SqlDbType.NVarChar).Value = TxtAdresa.Text;
command.Parameters.Add("#BrojTel", SqlDbType.NVarChar).Value = TxtBrojTel.Text;
command.Parameters.Add("#BrojLK", SqlDbType.NVarChar).Value = TxtBrojLK.Text;
cs.Open();
command.ExecuteNonQuery();
cs.Close();
RefreshTable();
ClearTxtBx();
}
}
//Pretraga postojećih Davalaca
private void TxtIme_TextChanged(object sender, EventArgs e)
{
(DgDavaoci.DataSource as DataTable).DefaultView.RowFilter = string.Format("Ime LIKE '{0}%'", TxtIme.Text);
}
}
}
}
Here is the MockUp of the Form before I begin to type/search/insert Data that isn't already in the Table (First Textbox*).
And after I start typing Name(Име) that starts with an "A" (name that isn't already in the Table).
I want to Search DB for that Column, but if there aren't any existing names, I want to be able to continue typing (without interuption) so that I can Insert new data into table.
DgDavaoci.CurrentRow in your DgDavaoci_SelectionChanged method is null, so attempting to access DgDavaoci.CurrentRow.Cells["DavaocID"] throws the NullReferenceException. The reason, best I can tell, is as follows:
You begin to type a value into your text box, a value that happens not to be found in the data set. As you type, you cause the TxtIme_TextChanged method to execute. It filters according to your search, and since the value is not found, it filters out every row in the set. Here's the important part: whenever the data set is filtered, it has the possibility of causing DgDavaoci_SelectionChanged to execute. Since the selection changed from the first row to no row at all (since there are no filtered rows to display), this method does execute. Now, when the method attempts to access the current row, there is no current row, and so we get a null here. Attempting to access a field of null throws the exception you're getting.
How can you fix this behavior? A simple null-check in DgDavaoci_SelectionChanged should do the trick. It looks to me like you can simply return from that method if(DgDavaoci.CurrentRow == null), or you can code in additional behavior. Just perform a check so that you don't reference the null object.
Probably the filter inside TxtIme_TextChanged is causing the DataGridView's SelectionChanged event to fire and the code is entering DgDavaoci_SelectionChanged. The exception indicates that DgDavaoci.CurrentRow is null, so you'll need to handle the case where DgDavaoci.CurrentRow is null in DgDavaoci_SelectionChanged.
A simple way to deal with this would be to just check DgDavaoci.CurrentRow is null and return from the function if that evaluates to true.
private void DgDavaoci_SelectionChanged(object sender, EventArgs e)
{
if (DgDavaoci.CurrentRow is null)
{
return;
}
ds.Tables["TblAkcije"].DefaultView.RowFilter = "DavaocID =" +
DgDavaoci.CurrentRow.Cells["DavaocID"].Value;
DgAkcije.DataSource = ds.Tables["TblAkcije"];
}
It looks like you might have a second DataGridView (DgAkcije) that is designed to show the details of the currently selected row in DgDavaoci. So, another approach might be to just clear DgAkcije if DgDavaoci.CurrentRow is null.
private void DgDavaoci_SelectionChanged(object sender, EventArgs e)
{
if (DgDavaoci.CurrentRow is null)
{
DgAkcije.DataSource = null; //I'm not 100% sure this will work, I haven't tested it.
return;
}
ds.Tables["TblAkcije"].DefaultView.RowFilter = "DavaocID =" +
DgDavaoci.CurrentRow.Cells["DavaocID"].Value;
DgAkcije.DataSource = ds.Tables["TblAkcije"];
}
Ultimately, however, you'll have to decide what you want to happen when DgDavaoci_SelectionChanged is called but DgDavaoci.CurrentRow is null.
Solution if anyone else is interested:
//Povezuje DataGridViews Davaoca i Akcija
private void DgDavaoci_SelectionChanged(object sender, EventArgs e)
{
if (DgDavaoci.CurrentRow != null)
{
ds.Tables["TblAkcije"].DefaultView.RowFilter = "DavaocID =" + DgDavaoci.CurrentRow.Cells["DavaocID"].Value;
DgAkcije.DataSource = ds.Tables["TblAkcije"];
}
}

How to get user input passed through to my query and display results in a label

I have another question posted where my query would not return the results into my sealresult Label. So I figured to ask it in a different way because I still cannot figure this out. I have the following code, it runs perfectly when the button "Search" is clicked and returns the query result. However, I have a textBox with an Id of receiptbox and I want to enable an user to input text and that be placed into the query to gather the result into the sealresult Label. How do I accomplish this? I want user input where it says RE00007544 from a textbox labeled receiptbox.
protected void receiptbox_TextChanged(object sender, EventArgs e)
{
}
protected void sealresultquery_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
}
protected void searchbutton_Click(object sender, EventArgs e)
{
sealresult.Text = "";
string connString = #"Data Source=SQL;Initial Catalog=mydatabase;User ID=admin;Password=******";
string query = "Select seal1 from dbo.RECEIPTHEADER where receipt = 'RE00007544'";
SqlConnection conn = new SqlConnection(connString);
SqlCommand comm = new SqlCommand(query, conn);
using (conn)
{
try
{
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
while(reader.Read())
{
sealresult.Text += reader[0].ToString();
}
reader.Close();
}
catch(Exception ex)
{
querystatus.Text = ex.Message;
}
}
}
If I understand, I think the simplest modification to the code you provided would be:
string query = "Select seal1 from dbo.RECEIPTHEADER where receipt = '" + receiptbox.Text + "'";
However, it's not the most secure way. You shouldn't be this trusting with user input.
Learn to use parameters which will save you from sql injections.
Change your code like below.
string query = "Select seal1 from dbo.RECEIPTHEADER where receipt = #number";
//define parameters used in command object
SqlParameter param = new SqlParameter();
param.ParameterName = "#number";
param.Value = receiptbox.Text.Trim();
//add new parameter to command object
comm.Parameters.Add(param);

search an item by name and display the content in another page

I want to display an item information in gridview from data base by using it name , and i want the gridview to be in another page
i tried this code,,but it didn't work
in the first page
protected void Page_Load(object sender, EventArgs e)
{
}
public string txt
{
get
{
// Return the actual name if it is not null.
return TextBox1.Text ?? string.Empty;
}
}
}
in the second page
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=FATIMAH;Initial Catalog=makeup;Integrated Security=True");
string find = "select * from product where(name like '%' +#name+ '%')";
SqlCommand comm = new SqlCommand(find, con);
comm.Parameters.Add("#name", SqlDbType.NChar).Value = txt;
con.Open();
comm.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
DataSet ds = new DataSet();
da.Fill(ds, "name");
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
}
You can pass parameter to another page using QueryString. onclick event of button on First page do this:-
protected void Button1_Click(object sender, EventArgs e)
{
string search_word = TextBox1.Text.ToString();
Response.Redirect("~/secondpage.aspx?srch_word=" + search_word);
}
and on second page request the querystring:-
protected void Page_Load(object sender, EventArgs e)
{
string search = Request.QueryString["srch_word"];
//execute sql query to perform search operation
}
Your query looks off to me. Try "select * from product where name like '%#name%'"
Also for your parameters you can just cmd.Parameters.AddWithValue("name", nameVariable);
Not sure why you would need to specify the type in this situation.
your problem is not the SQL query, your problem is passing parameter to another page.
for this reason you can do it in at least 4 different ways.
Send Text by query string
Pass it via Post Data
Pass it via Cookie
Send it via Session
in this case you can use query string, but you have to care about security issue.
BTW, it depends on how you redirect to 2th page.

Find a specific record in Access and display the records into textboxes

Hey Im new to stacoverflow and would like to ask some help. I need to type a ID into a textbox and when searched is clicked it will find the record and display each of the colum values to text boxes. Im using a access database. I have found solution on this but they dont seem to work. I have found and ajusted the following code but give an error op conn.open() and is coded in C#. Please help me.
source Code:
public partial class FamilyTree : UserControl
{
private OleDbConnection conn;
public FamilyTree()
{
InitializeComponent();
}
private void FamilyTree_Load(object sender, System.EventArgs e)
{
}
private void ConnectToDatabase()
{
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Hannes\Documents\Visual Studio 2013\Projects\fam\fam\Prog.mdb");
conn.Open();
}
private void DisconnectDatabase()
{
conn.Close();
}
private void btnSearch_Click(object sender, System.EventArgs e)
{
string title = txtID.Text.ToString();
string queryString = "SELECT * FROM FamilyTree" + txtID ;
OleDbCommand command = new OleDbCommand();
command.CommandText = queryString;
command.Connection = conn;
conn.Open();
OleDbDataReader dr = command.ExecuteReader();
while (dr.Read())
{
txtSex.Text += dr["gendre"].ToString();
txtColour.Text += dr["name"].ToString();
txtDOB.Text += dr["DOB"].ToString();
txtStatus.Text += dr["city"].ToString();
txtCock.Text += dr["mom"].ToString();
txtHen.Text += dr["dad"].ToString();
}
conn.Close();
}
Ensure that the 'ConnectToDatabase()' method is called somewhere before using 'conn' in btnSearch_Click.
Next, decide whether you are using the Id or Title to filter the result.
When creating the queryString, ensure you use the 'WHERE Id = ' or 'WHERE Title = ' clause to filter - but also ensure that you have a space between the end of the queryString and the value added at the end - the example you have given would produce 'SELECT * FROM FamilyTree23' if the Id was 23. This would error because there is no table with this name in the database.
Finally, as mentioned in other answers, 'using' a database connection, and using query parameters are a better practice. The 'using' statement will release the connection automatically after use, and a parameterised query prevent will SQL Injection issues and ensure correct data types are passed to the query.
Example:
public partial class FamilyTree : UserControl
{
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Hannes\Documents\Visual Studio 2013\Projects\fam\fam\Prog.mdb";
public FamilyTree()
{
InitializeComponent();
}
private void FamilyTree_Load(object sender, System.EventArgs e)
{
}
private void btnSearch_Click(object sender, System.EventArgs e)
{
string title = txtID.Text.ToString();
sqlQuery = "SELECT * FROM FamilyTree WHERE Title = ?";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand(sqlQuery, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("Title", title);
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
txtSex.Text += dr["gendre"].ToString();
txtColour.Text += dr["name"].ToString();
txtDOB.Text += dr["DOB"].ToString();
txtStatus.Text += dr["city"].ToString();
txtCock.Text += dr["mom"].ToString();
txtHen.Text += dr["dad"].ToString();
}
}
}
}
}

How to pass modified table name in SQL connection in ASP

I'm using SQL Server 2008 as my database in asp.net. And I'm passing the table name while at the time of clicking the <a> tag to web form. So how can I achieve this thing that when I click any link it change its sql query according to the value it receive?
For example:
<li class="last">
Item 1.1
</li>
Here cat contains the table name and sub contains the condition name.
And at the other side I'm doing:
SqlConnection con=new SqlConnection("Data Source=ANURAG-PC;Initial Catalog=dbPortal;Persist Security Info=True;User ID=sa;Password=anurag");
SqlDataAdapter da;
DataSet ds=new DataSet();
static DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
string s = Request.QueryString["cat"];
string s1 = Request.QueryString["sub"];
da = new SqlDataAdapter("select * from Architect where subcategory3='" + s1 + "'",con);
da.Fill(ds,"tab");
dt = ds.Tables["tab"];
DataGrid1.DataSource = dt;
DataGrid1.DataBind();
}
}
So I just want that insted of giving table name Architect I just want to pass s - how can I do that?
I would suggest that you think of other solution for this because what you are currently doing will lead to a very simple SQL Injection and your database will be at a great risk. I suggest that you have an enum of all tables and pass the id of the table in the query string instead of the table name and also you should make sure that the condition string is valid from any sql injection before making the string concatination
Your design isn't really optimal; is it possible to consider storing all data in a central table linked to both Category and SubCategory?
There are several weaknesses; any string concatenation of sql leaves you open to SqlInjection attacks. Even if you are choosing values from drop down lists, for example, it is still possible for client side script to modify the values in your combo boxes, or for an attacker to simply post data to your server side event handler.
In addition, having to source data from several tables means that you may have to deal with different schemas in your results; if you expect this (i.e. some tables will have more columns than others) then you can handle it appropriately.
Your query would then become something similar to:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
string s = Request.QueryString["cat"];
string s1 = Request.QueryString["sub"];
if(String.IsNullOrEmpty(s) || String.IsNullOrEmpty(s1)) { return; } //Improve Validation and error reporting
using(SqlConnection conn = new SqlConnection("Data Source=ANURAG-PC;Initial Catalog=dbPortal;Persist Security Info=True;User ID=sa;Password=anurag"))
{
using(SqlCommand command = new SqlCommand(conn))
{
command.CommandType = CommandType.Text;
command.CommandText = "SELECT * FROM Table WHERE Category = #Category AND SubCategory = #SubCategory";
command.Parameters.Add(new SqlParameter() { Type = SqlDbType.String, Name = "#Category", Value = s });
command.Parameters.Add(new SqlParameter() { Type = SqlDbType.String, Name = "#SubCategory", Value = s1 });
conn.Open();
using(SqlDataReader reader = command.ExecuteReader())
{
DataTable data = new DataTable("MyData");
data.Load(reader);
DataGrid1.DataSource = data;
DataGrid1.DataBind();
}
}
}
}
}
If you are stuck with your original model, then you may want to whitelist the table names so you can stick with parameterised queries:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
string s = Request.QueryString["cat"];
string s1 = Request.QueryString["sub"];
if(String.IsNullOrEmpty(s) || String.IsNullOrEmpty(s1)) { return; } //Improve Validation and error reporting
using(SqlConnection conn = new SqlConnection("Data Source=ANURAG-PC;Initial Catalog=dbPortal;Persist Security Info=True;User ID=sa;Password=anurag"))
{
using(SqlCommand command = new SqlCommand(conn))
{
command.CommandType = CommandType.Text;
switch(s)
{
case "Architect":
command.CommandText = "SELECT * FROM Architect WHERE SubCategory = #SubCategory";
break;
case "SomethingElse":
command.CommandText = "SELECT * FROM SomethingElse WHERE SubCategory = #SubCategory";
break;
default:
return; //Again, improve error handling
}
command.Parameters.Add(new SqlParameter() { Type = SqlDbType.String, Name = "#SubCategory", Value = s1 });
conn.Open();
using(SqlDataReader reader = command.ExecuteReader())
{
DataTable data = new DataTable("MyData");
data.Load(reader);
DataGrid1.DataSource = data;
DataGrid1.DataBind();
}
}
}
}
}
One comment I would make though, is that even if you implement either of the examples above, you still have a big problem; your data access code, business logic, and presentation code are all now munged into the code behind for this page. You will have to repeat this everywhere you need it leading to plenty of duplication, which is especially a problem when you need to fix bugs.
Instead, you might consider creating classes or using an ORM to handle all of this work for you, so you instead request a list of Architect objects, or a list of SomethingElse from a class or component, thus leaving the aspx to deal with the presentation. There is also a discussion here about why you might not want to use an ORM.
If you follow this route, your code might then become something like:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
string s = Request.QueryString["cat"];
string s1 = Request.QueryString["sub"];
//Still do validation on s and s1
ObjectFactory of = new ObjjectFactory();
DataGrid1.DataSource = ObjectFactory.GetObjects(s, s1);
DataGrid1.DataBind();
}
}
Effectively, it is now someone else's job to worry about how to get the objects, and to collect them, vastly reducing the code you have in your code behind. Plus you can easily reuse that across a wide variety of interfaces!
da = new SqlDataAdapter("select * from " + s + " where subcategory3='" + s1 + "'",con);
Like this ?
SqlConnection con=new SqlConnection("Data Source=ANURAG-PC;Initial Catalog=dbPortal;Persist Security Info=True;User ID=sa;Password=anurag");
SqlDataAdapter da;
DataSet ds=new DataSet();
static DataTable dt=new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
string s = Request.QueryString["cat"];
string s1 = Request.QueryString["sub"];
da = new SqlDataAdapter("select * from '"+s+"' where subcategory3='" + s1 + "'",con);
da.Fill(ds);
dt = ds.Tables[0];
DataGrid1.DataSource = dt;
DataGrid1.DataBind();
}
}

Categories

Resources