what is wrong with mySQL query in my application? - c#

I have a main form (formMain) which loads a user control (classification) in its load event. And in the load event of the user control classification it displays a datagridview. Let me show you the code.
CLASSIFICATION
string serverstring = "user id = root; password=; server=localhost; database=purchase_order; connection timeout=3;";
private void load_data()
{
MySqlConnection con = new MySqlConnection(serverstring);
try
{
string query = "SELECT * FROM tblclassification";
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.DataMember = dt.TableName;
}
catch (Exception)
{
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
Luckily it's working but when I click the search button located in another user control (search) it raises an event in the main form (formMain) wherein it must FILTER the datagridview in the user control (classification) but my code is not working.
Maybe I have a syntax error in my string query. Here is the code.
MAIN FORM
void SearchClicked(object sender, EventArgs e)
{
Search content = _searchbox;
classification control = new classification();
MySqlConnection con = new MySqlConnection(serverstring);
try
{
string query = "SELECT * FROM tblclassification WHERE class_name LIKE '%#search'";
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
//MessageBox.Show(content.txtboxSearch.Text);
cmd.Parameters.AddWithValue("#search", content.txtboxSearch.Text);
DataTable dt = new DataTable();
da.Fill(dt);
control.dataGridView1.DataSource = dt;
control.dataGridView1.DataMember = dt.TableName;
}
catch (Exception)
{
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}

use CONCAT()
string query = #"SELECT *
FROM tblclassification
WHERE class_name LIKE CONCAT('%', #search)";
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("#search", content.txtboxSearch.Text);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);

try
"SELECT * FROM purchase_order.tblclassification WHERE class_name LIKE ('%#search%')";
or ..
"SELECT * FROM tblclassification WHERE (class_name LIKE '%#search%')"

Related

NullReferenceException when using SQL Queries WPF C#

I am doing a little project and I got stuck at a certain point (I am new to C# WPF). What I want to do is I have some data tables called item, issue_note & items_in_Issue_Note. I want to get all the issue note details into a datagrid & after selecting a row and click view button, I want to display the items in that issue note. I can get the data using
dgISNDetails.ItemsSource = db.Issue_Note.ToList();
but when I am going to use
dgISNDetails.ItemsSource = db.Database.SqlQuery<Issue_Note>("select Issue_No,Created_Date,R_Name,R_Dep,R_Desig,Issued_Date,UpdatedAt from Issue_Note").ToList();
the code throws a NullReferenceException (I want to use the SQL query, because I want to search issue notes by no and date).
I will add my code for reference.
Thank you!
public PnlISNDetails_SK()
{
InitializeComponent();
dgISNDetails.ItemsSource = db.Database.SqlQuery<Issue_Note>("select Issue_No,Created_Date,R_Name,R_Dep,R_Desig,Issued_Date,UpdatedAt from Issue_Note").ToList();
dgISNDetails.ItemsSource = db.Issue_Note.ToList();
datagrid = dgISNDetails;
}
private void btnSearch_Click(object sender, RoutedEventArgs e)
{
dt = new DataTable();
addIssueNoteLogic = new AddIssueNoteLogic();
if(cmbSearchBy.Text== "ISSUE NOTE NO")
{
addIssueNoteLogic.ViewISNFromISNNo(txtSearchBox.Text).Fill(dt);
dgISNDetails.ItemsSource = dt.DefaultView;
datagrid = dgISNDetails;
}
else if (cmbSearchBy.Text == "CREATED DATE")
{
addIssueNoteLogic.ViewISNFromCreatedDate(Convert.ToDateTime(dpSearchDatePicker.Text)).Fill(dt);
dgISNDetails.ItemsSource = dt.DefaultView;
datagrid = dgISNDetails;
}
else if (cmbSearchBy.Text == "ISSUED DATE")
{
addIssueNoteLogic.ViewISNFromIssuedDate(Convert.ToDateTime(dpSearchDatePicker.Text)).Fill(dt);
dgISNDetails.ItemsSource = dt.DefaultView;
datagrid = dgISNDetails;
}
}
Class code for search issue notes:
public SqlDataAdapter ViewISNFromISNNo(string searchText)
{
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "select * from Issue_Note where Issue_No like '%" + searchText + "%'";
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Close();
return da;
}
public SqlDataAdapter ViewISNFromCreatedDate(DateTime searchText)
{
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "select * from Issue_Note where created_date = '" + searchText + "'";
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Close();
return da;
}
public SqlDataAdapter ViewISNFromIssuedDate(DateTime searchText)
{
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "select * from Issue_Note where Issued_date = '" + searchText + "'";
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Close();
return da;
}
public SqlDataAdapter ViewISNDetails(string isnNo)
{
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "select Item.ItemCode,Item.itemName,Item.Unit,Items_In_Issue_Note.Issued_Qty,Issue_Note.Issue_No from ((Item inner join Items_In_Issue_Note on Item.ItemCode= " +
"Items_In_Issue_Note.ItemCode) inner join Issue_Note on Issue_Note.Issue_No = Items_In_Issue_Note.Issue_No)where Issue_Note.Issue_No = '"+isnNo+"'; ";
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Close();
return da;
}
This is the code for displaying items in issue note:
public void LoadGrid()
{
dt = new DataTable();
string isnNo = (PnlISNDetails_SK.datagrid.SelectedItem as Issue_Note).Issue_No; //Exception is thrown in here
addIssueNoteLogic = new AddIssueNoteLogic();
addIssueNoteLogic.ViewISNDetails(isnNo).Fill(dt);
dgItemsInISN.ItemsSource = dt.DefaultView;
}
Debug and verify that the connection to the database in your datacontext is not null or closed. specifically this part
db.Database

I am created combobox in datagridview and it retrive the data through database, I want when I run the page combobox shows the default value

I am working on windows application,combo box works perfectly but by default when I run the page ,it shows blank , I want to show the default value.I am using this code.
public void combofill()
{
cmb.Items.Clear();
cmb.Items.Add("select");
SqlConnection con = new SqlConnection(con1);
con.Open();
SqlCommand cmd = new SqlCommand("Select Name from mr000 where Type&0x0f=3", con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
cmb.DataSource = dt;
cmb.Name = "combocust";
cmb.DisplayMember = "Name";
cmb.HeaderText = "Change Customer";
dataGridView1.Columns.Insert(3, cmb);
con.Close();
}
try this code
public void FillCmbo(String Sql, ComboBox cmb, String name)
{
try
{
if (Con.State == ConnectionState.Open)
Con.Close();
Con.Open();
SqlConnection con = new SqlConnection(Sql, Con);
SqlCommand cmd = new SqlCommand("Select Name from mr000 where Type&0x0f=3", con);
DataTable dt = new DataTable();
con.Fill(dr);
dt.Rows.InsertAt(Drw, 0);
cmb.Name = "combocust";
cmb.DisplayMember =name;
cmb.HeaderText = "Change Customer";
cmb.DataSource = dt;
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Check", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
you can also use
ComboBox.selectIndex=0;

Saving edits to database made in datagridview

How can I adapt my code to any changes that are made remain persistent?
As I understand I need to update the datatable which in turn will update the database. So I have tried to use the update command like below on a button click event.
adb.Update(dt);
However this doesn't seem to work, so I am obviously missing something, but I'm not sure what?.
Code
String ConnStr = "Data Source=database.com\\sqlexpress; Initial Catalog=Data; User ID=mobile; Password=password";
String SQL = "SELECT stationID, LocationName, plandate, username, status FROM dbo.joblist WHERE username = #username and status = #status";
SqlConnection con = new SqlConnection(ConnStr);
try
{
con.Open();
}
catch (Exception)
{
MessageBox.Show(e.ToString());
}
SqlCommand command = new SqlCommand(SQL, con);
command.Parameters.Add("#username", SqlDbType.VarChar).Value = auditorCmb.Text;
command.Parameters.Add("#status", SqlDbType.VarChar).Value = statusCmb.Text;
SqlDataAdapter adb = new SqlDataAdapter(command);
using (DataTable dt = new DataTable())
{
try
{
adb.Fill(dt);
dataGridView1.AutoResizeColumns();
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
con.Close();
}
catch
{
MessageBox.Show(e.ToString());
}
dataGridView1.DataSource = dt;
}
As far as I know SqlDataAdapter does not generate insert, update or delete commands on its own.
You have to either set them manually - https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.selectcommand(v=vs.110).aspx.
Or generate them with SqlCommandBuilder:
public static DataSet SelectSqlRows(string connectionString,
string queryString, string tableName)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(queryString, connection);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
connection.Open();
DataSet dataSet = new DataSet();
adapter.Fill(dataSet, tableName);
//code to modify data in DataSet here
builder.GetUpdateCommand();
//Without the SqlCommandBuilder this line would fail
adapter.Update(dataSet, tableName);
return dataSet;
}
}

How to get list of all database from sql server in a combobox using c#.net

I am entering the source name userid and password through the textbox and want the database list should be listed on the combo box so that all the four options sourcename, userid, password and databasename can be selected by the user to perform the connectivity
The databases are to be retrieve from other system as per the user. User will enter the IP, userid and password and they should get the database list in the combo box so that they can select the required database and perform the connectivity
private void frmConfig_Load(object sender, EventArgs e)
{
try
{
string Conn = "server=servername;User Id=userid;" + "pwd=******;";
con = new SqlConnection(Conn);
con.Open();
da = new SqlDataAdapter("SELECT * FROM sys.database", con);
cbSrc.Items.Add(da);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I am trying to do this but it is not generating any data
sys.databases
SELECT name
FROM sys.databases;
Edit:
I recommend using IDataReader, returning a List and caching the results. You can simply bind your drop down to the results and retrieve the same list from cache when needed.
public List<string> GetDatabaseList()
{
List<string> list = new List<string>();
// Open connection to the database
string conString = "server=xeon;uid=sa;pwd=manager; database=northwind";
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
// Set up a command with the given query and associate
// this with the current connection.
using (SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con))
{
using (IDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
list.Add(dr[0].ToString());
}
}
}
}
return list;
}
First add following assemblies:
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.Smo.dll
from
C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\
and then use below code:
var server = new Microsoft.SqlServer.Management.Smo.Server("Server name");
foreach (Database db in server.Databases) {
cboDBs.Items.Add(db.Name);
}
you can use on of the following queries:
EXEC sp_databases
SELECT * FROM sys.databases
Serge
Simply using GetSchema method:
using (SqlConnection connection = GetConnection())
{
connection.Open();
DataTable dtDatabases = connection.GetSchema("databases");
//Get database name using dtDatabases["database_name"]
}
using (var connection = new System.Data.SqlClient.SqlConnection("ConnectionString"))
{
connection.Open();
var command = new System.Data.SqlClient.SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "SELECT name FROM master.sys.databases";
var adapter = new System.Data.SqlClient.SqlDataAdapter(command);
var dataset = new DataSet();
adapter.Fill(dataset);
DataTable dtDatabases = dataset.Tables[0];
}
How to get list of all database from sql server in a combobox using c# asp.net windows application
try
{
string Conn = "server=.;User Id=sa;" + "pwd=passs;";
SqlConnection con = new SqlConnection(Conn);
con.Open();
SqlCommand cmd = new SqlCommand();
// da = new SqlDataAdapter("SELECT * FROM sys.database", con);
cmd = new SqlCommand("SELECT name FROM sys.databases", con);
// comboBox1.Items.Add(cmd);
SqlDataReader dr;
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
//comboBox2.Items.Add(dr[0]);
comboBox1.Items.Add(dr[0]);
}
}
// .Items.Add(da);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Try this:
SqlConnection con = new SqlConnection(YourConnectionString);
SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cbSrc.Items.Add(dr[0].ToString());
}
con.Close();
or this:
DataSet ds = new DataSet();
SqlDataAdapter sqlda = new SqlDataAdapter("SELECT name from sys.databases", YourConnectionString);
sqlda.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
cbSrc.Items.Add(ds.Tables[0].Rows[i][0].ToString());
}
public static List<string> GetAllDatabaseNamesByServerName(string ServerName, [Optional] string UserID, [Optional] string Password)
{
List<string> lstDatabaseNames = null;
try
{
lstDatabaseNames = new List<string>();
//string servername = System.Environment.MachineName;
string newConnString = string.Format("Data Source={0};", ServerName);
if (UserID == null)
{
newConnString += "Integrated Security = True;";
}
else
{
newConnString += string.Format("User Id ={0}; Password={1};", UserID, Password);
}
SqlConnection con = new SqlConnection(newConnString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT name FROM master.sys.databases", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.Rows)
{
lstDatabaseNames.Add(row[0].ToString());
}
con.Close();
return lstDatabaseNames;
}
finally
{
}
}

Problem filling data table with SQL adapter in ASP.NET

I have a username db table that I'm trying to connect with to compare the username/pass.
Here is my code, it's not working, what am I doing wrong?
DataTable dt = null;
protected void btn_Click_Login(object sender, EventArgs e)
{
string query = string.Format("SELECT * FROM Users WHERE Username='{0}' AND Password='{1}'", txtUsername.Text, txtPassword.Text);
using (SqlConnection c = new SqlConnection(ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString))
{
c.Open();
using (SqlDataAdapter a = new SqlDataAdapter(query, c))
{
DataTable t = new DataTable();
a.Fill(t);
}
}
if (dt.Rows.Count > 0)
{
Session["Username"] = txtUsername.Text;
Session["Password"] = txtPassword.Text;
Response.Redirect("main.aspx");
lblError.Text = "success";
}
else
{
lblError.Text = "Wrong Username/Password combination";
}
}
}
most probably you are using wrong datatable to check no of rows returned.
Check for t and dt instances of datatable.
Try creating a SqlCommand to hold your query.
SqlCommand cmd = new SqlCommand(query, c);
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
DataTable t = new DataTable();
a.Fill(t);
}
I'm not 100% sure that's your issue, but back in the days when i used to use ADO.NET (before L2SQL/EF, dark days indeed), i seem to remember an issue with DataTable's and SqlDataAdapter.
From what i remember - you can't fill a DataTable with a SqlDataAdapter based on a raw query string - you need to use SqlCommand. But i believe this can be accomplished with DataSet.
So either change to SqlCommand, or change to DataSet.
You fill t:
DataTable t = new DataTable();
a.Fill(t);
but read dt:
if (dt.Rows.Count > 0)
I decided to try the data reader and got it working:
protected void btn_Click_Login(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RbConnectionString"].ConnectionString);
conn.Open();
string queryString = "SELECT * FROM [Users] WHERE Username=#username AND Password= #password";
SqlCommand command = new SqlCommand(queryString, conn);
command.Parameters.AddWithValue("#username", txtUsername.Text);
command.Parameters.AddWithValue("#password", txtPassword.Text);
SqlDataReader reader = null;
reader = command.ExecuteReader();
if (reader.Read())
{
Session["Username"] = txtUsername.Text;
Session["Password"] = txtPassword.Text;
Response.Redirect("main.aspx");
}
else
{
lblError.Visible = true;
lblError.Text = "Incorrect Username/Password Combination";
}
conn.Close();
}
What error you are getting is not clear. But i feel your connection is open and is never closed. Try
c.Close();

Categories