I have problem with Arabic character display in textbox using SQL database. I use the nvarchar type in SQL and when I select a Latin character in item combobox its work perfectly (img1), but when i try to select an Arabic item in combobox nothing happen in textbox 1 and 2 (img2).
The code :
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
namespace testconnection
{
public partial class Form1 : Form
{
private SqlConnection con;
private SqlCommand cmd;
private SqlDataAdapter da;
private DataTable dt;
private SqlDataReader dr;
public Form1()
{
InitializeComponent();
combo();
}
void combo()
{
con = new SqlConnection(
#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\vemmi\Documents\user.mdf;Integrated Security=True");
con.Open();
cmd = new SqlCommand("SELECT usrs FROM usrtest", con);
try
{
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
comboBox1.Items.Add(dr["usrs"]);
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button2_Click(object sender, EventArgs e)
{
Form2 c = new Form2();
c.ShowDialog();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
con = new SqlConnection(
#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\vemmi\Documents\user.mdf;Integrated Security=True");
con.Open();
cmd = new SqlCommand("SELECT * FROM usrtest WHERE usrs like '" + comboBox1.Text + "' ");
cmd.Connection = con;
try
{
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string p = dr["pwd"].ToString();
string n = dr["nbr"].ToString();
textBox2.Text = p;
textBox3.Text = n;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
enter image description here
Try adding 'N' before the Arabic string in the query.
cmd = new SqlCommand("SELECT * FROM usrtest WHERE usrs like N'" + comboBox1.Text + "' ");
Related
I am developing windows application .Net in C#
DB stored inside the C# Application ".....\SQliteExample\SQliteExample\bin\Debug\MyDatabase.sqlite"
I can insert,update ,view and Delete to the table with the above code and view its contents in another activity with no troubles at all. However, when I restart the application I found that what I have inserted data before I restart the application has gone!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SQLite;
namespace SQliteExample
{
public partial class Form1 : Form
{
SQLiteConnection connection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
public Form1()
{
InitializeComponent();
SQLiteConnection.CreateFile("MyDatabase.sqlite");
connection.Open();
string sql = "create table Employee1 (EmpID int,EmpName varchar(20), age int,Salary int,Phone int , Address Varchar(20))";
SQLiteCommand command = new SQLiteCommand(sql, connection);
command.ExecuteNonQuery();
connection.Close();
}
private void btnSave_Click(object sender, EventArgs e)
{
if (connection.State != ConnectionState.Open)
connection.Open();
string sql1 = "insert into Employee1 (EmpID,EmpName,Age,Salary,Phone,Address) values (?,?,?,?,?,?)";
SQLiteCommand command = connection.CreateCommand();
command.CommandText = sql1;
command.Parameters.AddWithValue("EmpID", textBox1.Text);
command.Parameters.AddWithValue("EmpName", textBox2.Text);
command.Parameters.AddWithValue("Age", textBox3.Text);
command.Parameters.AddWithValue("Salary", textBox4.Text);
command.Parameters.AddWithValue("Phone", textBox5.Text);
command.Parameters.AddWithValue("Address", textBox6.Text);
command.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Data Saved");
Clear();
View();
}
private void Clear()
{
textBox1.Text = string.Empty;
textBox2.Text = string.Empty;
textBox3.Text = string.Empty;
textBox4.Text = string.Empty;
textBox5.Text = string.Empty;
textBox6.Text = string.Empty;
}
private void View()
{
string sql3 = "select * from Employee1 order by EmpID asc";
SQLiteCommand command3 = new SQLiteCommand(sql3, connection);
DataTable dt = new DataTable();
SQLiteDataAdapter da = new SQLiteDataAdapter(command3);
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
}
private void btnSelect_Click(object sender, EventArgs e)
{
View();
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
if (connection.State != ConnectionState.Open)
connection.Open();
string sql1 = "delete from Employee1 where EmpID = ?";
SQLiteCommand command = connection.CreateCommand();
command.CommandText = sql1;
command.Parameters.AddWithValue("EmpID", int.Parse(textBox1.Text));
command.ExecuteNonQuery();
connection.Close();
Clear();
View();
}
else
{
MessageBox.Show("Please Enter EmpID");
}
}
}
}
Thanks in Advance,
On recompilation you recreate the database file and recreate the table "employee". Therefore all your previous data is lost.
Apologies if this has been covered. The examples I seemed to find were more complicated than I need it to be
I'm trying to output the entire contents of an SQL table to a DatagridView when a button "Display All Records" is clicked
I'm having a bit of trouble, here is what I have so far
private void Button_Click_2(object sender, RoutedEventArgs e)
{
{
string query = "select * from student";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(DataGridView);
con.Close();
da.Dispose();
}
Here is all my code if you need to refer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
namespace WpfApplication4
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True");
public MainWindow()
{
InitializeComponent();
establishConnection();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Boolean postSuccess = false;
if (validation() == true)
{
SqlCommand details = new SqlCommand("INSERT INTO Student (Firstname, LastName, MatriculationNo, GradeOne, GradeTwo, GradeThree) VALUES (#FirstName, #LastName, #MatriculationNo, #GradeOne, #GradeTwo, #GradeThree)", con);
details.Parameters.AddWithValue("#FirstName", firstnameTextbox.Text);
details.Parameters.AddWithValue("#LastName", lastnameTextbox.Text);
details.Parameters.AddWithValue("#MatriculationNo", matriculationnoTextbox.Text);
details.Parameters.AddWithValue("#GradeOne", Component1Textbox.Text);
details.Parameters.AddWithValue("#GradeTwo", Component2Textbox.Text);
details.Parameters.AddWithValue("#GradeThree", Component3Textbox.Text);
con.Open();
details.ExecuteNonQuery();
postSuccess = true;
if (postSuccess)
{
MessageBox.Show("Details entered succesfully!");
firstnameTextbox.Clear();
lastnameTextbox.Clear();
matriculationnoTextbox.Clear();
Component1Textbox.Clear();
Component2Textbox.Clear();
Component3Textbox.Clear();
}
else
{
MessageBox.Show("Data not entered succesfully, please check DB connection");
}
con.Close();
}
}
private void establishConnection()
{
try
{
con.Open();
System.Diagnostics.Debug.Print("Connected to SQL database");
connectionLabel.Content = "Connected to SQL Database";
con.Close();
}
catch (Exception)
{
connectionLabel.Content = "not connected to sql database";
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
firstnameTextbox.Clear(); //Clears the first name textbox
lastnameTextbox.Clear(); //Clears the last name textbox
matriculationnoTextbox.Clear(); //Clears the Matriculation Number textbox
Component1Textbox.Clear(); //Clears the component one textbox
Component2Textbox.Clear(); //Clears the component two textbox
Component3Textbox.Clear(); //Clears the component three textbox
}
private Boolean validation()
{
if (!Regex.Match(firstnameTextbox.Text, "^[A-Z][a-zA-Z]*$").Success)
{
MessageBox.Show("Please Enter a valid First Name");
firstnameTextbox.Clear();
return false;
}
else
{
return true;
}
}
private void Button_Click_3(object sender, RoutedEventArgs e)
{
con.Open();
string sql = #"DELETE FROM Student;"; //Deleting all from Student table
SqlCommand purge = new SqlCommand(sql, con);
MessageBox.Show("Are you sure you want to purge the entire contents of the database?"); //Prompting user to make sure they want to delete
purge.ExecuteNonQuery(); //Execute purge query
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
{
string query = "select * from student";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(DataGridView);
con.Close();
da.Dispose();
}
}
}
}
Any help would be much appreciated, thank you
Just fill DataTable with your table and bind it to GridView.DataContext.
Like so:
First Add DataGrid in XAML editor <DataGrid Name="customDataGrid" ItemsSource="{Binding}">
then Code behind:
namespace WpfApplication4
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
string connectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True";
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DataTable table = null;
string query = "select * from student";
try
{
using (SqlConnection connection = new SqlConnection(this.connectionString))
{
connection.Open();
using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
{
table = new DataTable();
adapter.Fill(table);
}
}
}
catch (Exception ex)
{
//handle caught exception
}
if (table != null)
{
customDataGrid.DataContext = table.DefaultView;
}
}
}
}
Binding part: customDataGrid.DataContext = table.DefaultView;
try this....
private void Button_Click_2(object sender, EventArgs e)
{
string query = "select * from student";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
DataTable dt = new DataTable();
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(dt);
con.Close();
da.Dispose();
dataGridView1.DataSource = dt;
}
MySqlCommand command = conn.CreateCommand();
command.CommandText = "Select * from student";
try
{
con.Open();
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = command;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
con.Close();
Try this
I'm not really sure where the SqlConnection, SqlCommand and the Open()/Close() goes. I want to use just the single variable cmd throughout the program, hence not using the SqlCommand cmd = new SqlCommand('SELCT * FROM blabla); format.
EDIT: My code below results to the textbox having the text "System.Data.SqlClient.SqlCommand" when i click the button.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.SqlTypes;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection(#"Data Source=EDIOTH\SQLEXPRESS;
Initial Catalog=Try; Integrated Security=SSPI");
SqlCommand cmd = new SqlCommand();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
cmd.CommandText = "SELECT Pnt_Lname FROM PATIENT WHERE Pnt_ID = 1;";
txtBox1.Text = cmd.ToString();
con.Close();
}
}
}
you can create constant string to hold the connection string and then you can do as below in your button1_Click
you don't need to call the close method of sql connection when you use using block as below
using(SqlConnection con = new SqlConnection(connectionString))
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT Pnt_Lname FROM PATIENT WHERE Pnt_ID = 1";
con.Open();
txtBox1.Text =cmd.ExecuteScalar() as string;
}
And also if you need to read Pnt_Lname from database you better use ExecuteScalar method
You can use this structure. Use using to properly close and dispose of SqlConnection.
Also, you can define the connection string in your config file and use it from there.
using (SqlConnection conn = new SqlConnection(#"Data Source=EDIOTH\SQLEXPRESS;
Initial Catalog=Try; Integrated Security=SSPI"))
{
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT Pnt_Lname FROM PATIENT WHERE Pnt_ID = 1";
txtBox1.Text = (String)command.ExecuteScalar();
}
In case this would be of help to anyone, this is the answer to my question:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Book
{
public partial class frmBook : Form
{
SqlConnection con =
new SqlConnection(#"Data Source=EDIOTH\SQLEXPRESS;
Initial Catalog=XXDB; Integrated Security=SSPI");
SqlCommand cmd;
public frmBook()
{
InitializeComponent();
}
private void frmBook_Load(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("SELECT min(Book_ID) FROM Book;",con);
txtID.Text = cmd.ExecuteScalar().ToString();
cmd = new SqlCommand("SELECT title FROM Book WHERE Book_ID = '"
+ txtID.Text + "'", con);
txtTitle.Text = cmd.ExecuteScalar().ToString();
con.Close();
btnSave.Enabled = false;
}
private void btnNext_Click(object sender, EventArgs e)
{
int count = int.Parse(txtID.Text) + 1;
con.Open();
cmd = new SqlCommand("SELECT title FROM Book WHERE Book_ID = '"
+ count.ToString() +"'", con);
txtTitle.Text = cmd.ExecuteScalar().ToString();
txtID.Text = count.ToString();
con.Close();
}
private void btnNew_Click(object sender, EventArgs e)
{
txtID.Text = "";
txtTitle.Text = "";
txtAuthor.Text = "";
btnNew.Enabled = false;
btnSave.Enabled = true;
}
private void btnSave_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("INSERT INTO Book (Book_ID, Title, Author) " +
"VALUES ('"+ txtID.Text +
"','"+ txtTitle.Text +
"','"+ txtAuthor.Text +"');", con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data saved!");
btnSave.Enabled = false;
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
I'm trying to make an agenda facility for my winform project. I want to display database records on textBox for specific date when user chose date on monthCalendar control. Below you can see my db table design, my winform design and my code and exception message that i'm getting. How can i fix this?
*ps: no need to suggest on using parametrized queries. i can and i will change it eventually
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace EKS
{
public partial class Agenda : Form
{
public Agenda()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
panel1.BackColor = Color.FromArgb(100, 88, 55, 55);
}
private void button1_Click(object sender, EventArgs e)
{
try {
string myQuery = "insert into agenda (input_agenda, input_date) values ('"+textBox1.Text.ToString()+"', '"+ monthCalendar1.SelectionStart +"')";
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = "Data Source=localhost; database=EKS; uid=sa; pwd=123; connection lifetime=20; connection timeout=25; packet size=1024;";
SqlCommand myComm = new SqlCommand();
myComm.Connection = myConn;
myComm.CommandText = myQuery;
myConn.Open();
myComm.ExecuteNonQuery();
myConn.Close();
MessageBox.Show("agenda updated");
}
catch (Exception x) {
MessageBox.Show(x.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
try {
string deleteQuery = "DELETE FROM agenda WHERE input_date = '" + monthCalendar1.SelectionStart +"'";
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = "Data Source=localhost; database=EKS; uid=sa; pwd=123; connection lifetime=20; connection timeout=25; packet size=1024;";
SqlCommand myComm = new SqlCommand();
myComm.Connection = myConn;
myComm.CommandText = deleteQuery;
myConn.Open();
myComm.ExecuteNonQuery();
myConn.Close();
MessageBox.Show("delete succeeded");
}
catch(Exception x){
MessageBox.Show(x.ToString());
}
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
GetAgendaDetails(e.Start.Date);
}
private void GetAgendaDetails(DateTime x){
string myQuery = "select input_agenda from agenda where input_date = '" + x.Date.ToString() + "'";
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = "Data Source=localhost; database=EKS; uid=sa; pwd=123; connection lifetime=20; connection timeout=25; packet size=1024;";
try {
myConn.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand(myQuery,myConn);
myReader = myCommand.ExecuteReader();
while (myReader.Read()) {
textBox1.Text = myReader.GetString(100);
}
myConn.Close();
}
catch(Exception z){
MessageBox.Show(z.ToString());
}
}
}
}
Use DateSelected event of MonthCalendar control, Which will be fired when user selects a date.
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
AganedaInformation info = GetAgendaDetails(e.Start.Date);
}
Add a private method to query the database based on the passed selected date
Private AganedaInformation GetAgendaDetails(DateTime selectedDate)
{
//Add logic to query the database with the selected date and return the information
}
I am building a windows application using C#. In my login form, I'm getting Select Command property has not been initialized before calling fill method.
Here is the code:
public partial class frmlogin : Form
{
SqlConnection con = new SqlConnection("Data Source=TH07L019;Initial Catalog=loginerror;Integrated Security=True");
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter adp = new SqlDataAdapter();
public frmlogin()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmd.Connection = con;
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
cmd.CommandText = "select * from login where username='" + txt1.Text + "' and password='" + txt2.Text +"'";
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
frmmain main = new frmmain();
main.Show();
}
else
{
MessageBox.Show("Please enter correct name and passowrd", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
You have to specify select command of SqlDataAdapter before filling your table. You are not doing it. Your SqlCommand object is not connected in any way to your SqlDataAdapter.
adp.SelectCommand=cmd;
Another way to accomplish would be to simply pass the SQLCommand as an argument into your data adapter as follows -
SqlCommand cmd = new SqlCommand();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
SQL Data Adapter interacts with the data table. It is used to fill the Data Table from SQL Server DataBase. Before, filling the Data Table, the Data Adapter should know the command it is going to execute. So we have to fill the object of SQL Command Type i.e
SqlDataAdapter da = new SqlDataAdapter(cmd);
Here cmd is the object of SQL Command.
Now, the Data Adapter will know which command to execute before filling the data table.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Employees_Details_Management_System
{
public partial class ShowEmpDtlsFrm : Form
{
SqlConnection con = new SqlConnection(#"Data Source = (local); Initial Catalog = sp_emp; Integrated Security = True");
public SqlCommand cmd { get; private set; }
// private SqlCommand cmd;
public ShowEmpDtlsFrm()
{
InitializeComponent();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
ShwEmpDtlsLbl.Text = "Employee Database Management";
comboBox1.Text = "Click";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
public void DataGridChk()//Check if DataGrid is empty or not
{
if (dataGridView1.RowCount == 1)
{
dataGridView1.Visible = false;
MessageBox.Show("The Given " + comboBox1.Text+ " is Invalid \nEnter Valid " + comboBox1.Text);
}
}
public void DbDataFetch(String Qry)//For Fetching data from database
{
SqlCommand cmd = new SqlCommand(Qry, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "emp");
dataGridView1.DataSource = ds.Tables["emp"].DefaultView;
DataGridChk();
}
public void SrchBtn_Click(object sender, EventArgs e)
{
try
{
if (comboBox1.Text == "Employee ID" || comboBox1.Text == "Department ID" || comboBox1.Text == "Manager ID")
{
if (textBox1.Text != "")
{
con.Open();
dataGridView1.Visible = true;
if (comboBox1.Text == "Employee ID")
{
string Qry = "select * from emp where emp_id='" + textBox1.Text + "' ";
DbDataFetch(Qry);
}
else if (comboBox1.Text == "Department ID")
{
string Qry = "select * from emp where dep_id='" + textBox1.Text + "' ";
DbDataFetch(Qry);
}
else if (comboBox1.Text == "Manager ID")
{
string Qry = "select * from emp where manager_id='" + textBox1.Text + "' ";
DbDataFetch(Qry);
}
con.Close();
}
else
{
MessageBox.Show("Please Enter the ID...");
}
}
else
{
MessageBox.Show("Choose Valid Option...");
}
}
catch (System.Data.SqlClient.SqlException sqlException)
{
System.Windows.Forms.MessageBox.Show(sqlException.Message);
con.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
EmpDtlsFrm edf = new EmpDtlsFrm();
edf.Show();
this.Hide();
}
}
}