I have problem to get specific value from sql server with parameter can anybody explain me why it works on winfom but not on wpf and how i can fix it
my code:
private void UpdateItems()
{
COMBOBOX1.Items.Clear();
SqlConnection conn = new SqlConnection(Properties.Settings.Default.constring.ToString());
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM CLIENT where cod_cli='some_specific_string'", conn);
DataSet ds = new DataSet();
da.Fill(ds, "CLIENT");
COMBOBOX1.ItemsSource = ds.Tables[0].DefaultView;
COMBOBOX1.DisplayMemberPath = ds.Tables[0].Columns["FR"].ToString();
COMBOBOX1.SelectedValuePath = ds.Tables[0].Columns["FC"].ToString();
}
The program when execute this function crash with error:
System.Data.SqlClient.SqlException: 'Invalid column name
'some_specific_string'.'
the solution is
SqlConnection sqlConnection = new SqlConnection(Properties.Settings.Default.constring.ToString());
{
SqlCommand sqlCmd = new SqlCommand("SELECT * FROM CLIENTS where cod_cli=#cod", sqlConnection);
sqlCmd.Parameters.AddWithValue("#cod", cod_cli.Text);
sqlConnection.Open();
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
COMBOBOX1.Items.Add(sqlReader["FR"].ToString());
}
sqlReader.Close();
}
The query doesn't recognize string as parameter but adding as SQL parameter it works.
SqlConnection conn = new SqlConnection(Properties.Settings.Default.constring.ToString());
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM CLIENT where cod_cli='some_specific_string'", conn);
DataSet ds = new DataSet();
da.Fill(ds, "CLIENT");
//Populate the combobox
COMBOBOX1.ItemsSource = ds.Tables[0].DefaultView;
COMBOBOX1.DisplayMemberPath = "FR";
COMBOBOX1.SelectedValuePath = "FC";
where "FR" and "FC" are existing columns in your SELECT Query.
Related
//instantiating connection
dbConn = new SqlConnection("Data Source = local host; initial catalog=Project; Integrated Security = SSPI ");
ds = new DataSet();
//select everything from the table
dbCommand = new SqlCommand("SELECT * FROM Shops;", dbConn);
dbAdapter = new SqlDataAdapter(dbCommand);
//filling the datagrid
dbAdapter.Fill(ds, "All Shops");
dataGridView1.DataSource = ds.Tables["All Shops"];
To show data into datagrid you need to assign datasource and then use DataBind() to bind the data.
dataGridView1.DataSource = ds.Tables["All Shops"];
dataGridView1.DataBind(); // use this after assigning the datasource
private void GetResults()
{
//Establishing the MySQL Connection
MySqlConnection conn = new MySqlConnection("Database=potentiality_live;Data Source=eu;User Id=ptly;Password=phat40");
string query;
MySqlCommand SqlCommand;
MySqlDataReader reader;
MySqlDataAdapter adapter = new MySqlDataAdapter();
//Open the connection to db
conn.Open();
//Generating the query to fetch the contact details
query = "SELECT id,date_time,link FROM'sdfsdfsdf'";
SqlCommand = new MySqlCommand(query, conn);
adapter.SelectCommand = new MySqlCommand(query, conn);
//execute the query
reader = SqlCommand.ExecuteReader();
//Assign the results
GridView1.DataSource = reader;
//Bind the data
GridView1.DataBind();
}
Reference:
http://www.codeproject.com/Questions/453091/how-to-get-data-from-sql-database-to-gridview-by-c
the problem is i can use my database if my gridview is not connected to database using sqldatasource
it will work if my database is connected manually using code to gridview
i need a code to search my data using datagrid and textbox and button with the search code in it
here's my current code for search command
but its only working when i connect my datagrid to database manually using code
strconn = "select * from User_TBL_DB where (Lastname like '%' + #search +'%')";
SqlCommand xp = new SqlCommand(strconn, conn);
xp.Parameters.Add("#search", SqlDbType.NVarChar).Value = SearchBOX.Text;
conn.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataSet ds = new DataSet();
da.Fill(ds, "Name");
GridView2.DataSource = ds;
GridView2.DataBind();
conn.Close();
hope you can help me
SQL Command is not correct. It should be ... LIKE '%#Search%'
var ds = new DataSet();
using (var cnn = new SqlConnection(CONNECTION_STRING))
{
string cmdText = "SELECT * FROM User_TBL_DB WHERE Lastname LIKE '%#Search%'";
var cmd = new SqlCommand(cmdText, cnn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Search", SearchBOX.Text);
cnn.Open();
var da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds, "Name");
}
GridView2.DataSource = ds;
GridView2.DataBind();
how am i going prevent "lesson Title" from duplicating in database when user input duplicate data?
SqlConnection cnn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Project1ConnectionString"].ConnectionString;
cnn.Open();
cmd.CommandText = "select * from Lesson";
cmd.Connection = cnn;
da.SelectCommand = cmd;
da.Fill(ds, "Lesson");
DataRow drow = ds.Tables["Lesson"].NewRow();
drow["TopicID"] = DropDownList1.Text;
drow["LessonTitle"] = TextBox1.Text;
drow["LessonDate"] = DateTime.Now;
ds.Tables["Lesson"].Rows.Add(drow);
da.Update(ds, "Lesson");
That kind of uniqueness should be enforced by the database. Add a unique constraint to your table:
CREATE UNIQUE INDEX UK_Lesson_Title ON Lesson (Title)
You can create a function to check the duplicate LessonTitle.
Explanantion: here i have created a function called checkDuplicateTitle().
this function takes AllRows of a LessonTable as DataRowCollection and LessonTitle to be verified as inputs.
it will check the LessonTitle of each and every row.
if given LessonTitle is matched with existing Titles from Table then this function returns true else returns false.
if the returned value is true we will ignore the updating the table with new row as LessonTitle is already Existing otherwise we will add it.
Code as below:
void UpdateLessonTable()
{
SqlConnection cnn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Project1ConnectionString"].ConnectionString;
cnn.Open();
cmd.CommandText = "select * from Lesson";
cmd.Connection = cnn;
da.SelectCommand = cmd;
da.Fill(ds, "Lesson");
if (!checkDuplicateTitle(ds.Tables["Lesson"].Rows, textBox1.Text.ToString()))
{
DataRow drow = ds.Tables["Lesson"].NewRow();
drow["TopicID"] = DropDownList1.Text;
drow["LessonTitle"] = TextBox1.Text;
drow["LessonDate"] = DateTime.Now;
ds.Tables["Lesson"].Rows.Add(drow);
da.Update(ds, "Lesson");
}
else
{
//you can display some warning here
// MessageBox.Show("Duplicate Lesson Title!");
}
}
//function for checking duplicate LessonTitle
bool checkDuplicateTitle(DataRowCollection rowTitle,String newTitle)
{
foreach (DataRow row in rowTitle)
{
if(row["LessonTitle"].Equals(newTitle))
return true;
}
return false;
}
I've looked through the other questions related to this, but I'm having a different issue. I can't get a specific item to return, it only returns my column name. How do I get the item to return?
public static string GetOneFieldRecord(string field, string companyNum)
{
DataSet ds = new DataSet();
SqlCommand comm = new SqlCommand();
string strSQL = "SELECT #FieldName FROM Companies WHERE CompanyNum = #CompanyNum";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #connstring;
comm.Connection = conn;
comm.CommandText = strSQL;
comm.Parameters.AddWithValue("#FieldName", field);
comm.Parameters.AddWithValue("#CompanyNum", companyNum);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
conn.Open();
da.Fill(ds, "CompanyInfo");
conn.Close();
return ds.Tables[0].Rows[0].ItemArray[0].ToString();
}
I've also tried
return ds.Tables[0].Rows[0][0].ToString();
I'm just getting whatever is in the field variable.
If I pass in ("CompanyName", 33), it returns "CompanyName".
Your query (in sql profiler) is
SELECT 'CompanyName' FROM Сompanies WHERE СompanyNum = 33
So it returns exactly "CompanyName" string. You cannot pass column name as sqlparameter. You should do something like
public static string GetOneFieldRecord(string field, string companyNum)
{
DataSet ds = new DataSet();
SqlCommand comm = new SqlCommand();
string strSQL = string.Format("SELECT {0} FROM Companies WHERE CompanyNum = #CompanyNum", field);
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #connstring;
comm.Connection = conn;
comm.CommandText = strSQL;
comm.Parameters.AddWithValue("#FieldName", field);
comm.Parameters.AddWithValue("#CompanyNum", companyNum);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
conn.Open();
da.Fill(ds, "CompanyInfo");
conn.Close();
return ds.Tables[0].Rows[0].ItemArray[0].ToString();
}
But this code can be used for SQL injection.
To avoid Sql injection, you could check that fieldName in field variable is one of the table columns.
Or You could get SELECT * FROM Сompanies WHERE СompanyNum = #CompanyNum and get value of named column from datatable:
public static string GetOneFieldRecord(string field, string companyNum)
{
DataSet ds = new DataSet();
SqlCommand comm = new SqlCommand();
string strSQL = "SELECT * FROM Companies WHERE CompanyNum = #CompanyNum";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #connstring;
comm.Connection = conn;
comm.CommandText = strSQL;
comm.Parameters.AddWithValue("#FieldName", field);
comm.Parameters.AddWithValue("#CompanyNum", companyNum);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
conn.Open();
da.Fill(ds, "CompanyInfo");
conn.Close();
return ds.Tables[0].Rows[0][field].ToString();
}
I have the following C# code:
public string TargetDate()
{
SqlConnection con =
new SqlConnection("Server=localhost;Database=Timer;Trusted_Connectopn=True");
SqlCommand cmd = new SqlCommand("select * from Timer");
con.Open();
DataSet ds = new DataSet(cmd,con);
SqlDataAdapter da = new SqlDataAdapter();
da.Fill(ds);
con.Close();
}
but I get error at the: new DataSet(cmd,con); ...
the error: CS1502: The best overloaded
method match for
'System.Data.DataSet.DataSet(System.Runtime.Serialization.SerializationInfo,
System.Runtime.Serialization.StreamingContext)'
has some invalid arguments
What is could be the problem?
Try this:
SqlConnection con = new SqlConnection
("Server=localhost;Database=Timer;Trusted_Connection=True");
SqlCommand cmd = new SqlCommand("select * from Timer", con);
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
This is even better:
DataTable dataTable = new DataTable();
using(SqlConnection connection = new SqlConnection("Server=localhost;Database=Timer;Trusted_Connection=True"))
using(SqlCommand command = connection.CreateCommand())
{
command.CommandText = "select * from Timer";
connection.Open();
SqlDataReader reader = command.ExecuteReader();
dataTable.Load(reader);
}
You've got the wrong constructor for the DataSet. Try this
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(con);
It seems you have mixed up the constructors:
Try the following:
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(con);
Hope that helps