Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
C#
 private DataSet GetRecords(string TableName)
        { 
SqlCommand cmd = new SqlCommand();
            cmd.Connection = cn;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT * FROM " + TableName;
            SqlDataAdapter da;
            da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            DataSet ds = new DataSet();
            da.Fill(ds, TableName);
            return ds;
}


I want to add:
C#
"WHERE SupplierName= '" + txtsuppliername.text + "'";


How do you place a field name in the given code?
Posted
Updated 15-Jul-12 4:14am
v3
Comments
[no name] 15-Jul-12 10:17am    
I know how this sounds, but seriously? You went to all this trouble because you could not figure out, cmd.CommandText = "SELECT * FROM " + TableName + " WHERE SupplierName= '" + txtsuppliername.text + "'";? Did you do the least bit of research?
enhzflep 15-Jul-12 10:27am    
my +5
wolfsor 15-Jul-12 11:53am    
Thank you very much for your help. I don't have enough experience in programming and it gets really frustrating for me to work out these codes. Very much appreciated your help!

As Wes says - it's pretty obvious! But please, please, don't do it that way! Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead:
C#
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM " + TableName + " WHERE SupplierName=@SN";
cmd.Parameters.AddWithValue("@SN", txtSupplierName.Text);
 
Share this answer
 
Comments
wolfsor 15-Jul-12 11:53am    
thanks!
OriginalGriff 15-Jul-12 11:58am    
You're welcome!
C#
private DataSet GetRecords(string TableName)
        { 
 private string sql;
SqlCommand cmd = new SqlCommand();
sql="SELECT * FROM " + TableName + " ";
            cmd.Connection = cn;
            cmd.CommandType = CommandType.Text;
if (txtsuppliername.text!="")
{
sql + = " WHERE SupplierName= '" + txtsuppliername.text + "'" ; 
}
            cmd.CommandText = sql;
            SqlDataAdapter da;
            da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            DataSet ds = new DataSet();
            da.Fill(ds, TableName);
            return ds;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900