I have a 4 text boxes on a win form. [First Name, Last Name, Job, Description.]
I have one table.
I have the dataset and a data table configured and I can navigate the records.
I want to know how can I search based on first name, obtain the data from dataset/table and display the info based on what is in the text box.
how do I do this such as, obtain the row, "inc" where the
txtFirstName = ds.Tables[0].Column[1]
Then I can:
DataRow row = ds.Tables[0].Rows[inc];
txtFirstName.Text = row[1];
txtSurname.Text = row[2];
txtJobTitle.Text = row[3];
txtDepartment.Text = row[4];
sorry, found the solution.
First I created a search method which returned the row...
private int first_name_search(string fname)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if ((string)ds.Tables[0].Rows[i]["first_name"] == fname)
{
send = i;
//result stuff
break;
}
}
// return result;
return send;
}
I used this method in the Search button click method and displayed the data...
In a function that return a string[]:
string[number_of_infos] infos = null;
connection = new SqlConnection(connectionString);
connection.Open();
cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM your_table WHERE first_name = " + your_first_name;
cmd.Connection = connection;
rdr = cmd.ExecuteReader();
if(rdr.Read())
{
infos[0] = rdr["Surname"].ToString();
infos[1] = rdr["JobTitle"].ToString();
infos[2] = rdr["Department"].ToString();
}
cmd.Dispose();
connection.Close();
return infos;
Direct in your form:
connection = new SqlConnection(connectionString);
connection.Open();
cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM your_table WHERE first_name = " + your_first_name;
cmd.Connection = connection;
rdr = cmd.ExecuteReader();
if(rdr.Read())
{
txtSurname.Text = rdr["Surname"].ToString();
txtJobTitle.Text = rdr["JobTitle"].ToString();
txtDepartment.Text = rdr["Department"].ToString();
}
cmd.Dispose();
connection.Close();
return infos;
Else if you want to get the row infos:
foreach(DataGridViewRow row in your_DGV.Rows)
if(row["FirstName"].Value.ToString() == txtFirstName.Text)
{
txtSurname.Text = row["Surname"].Value.ToString();
txtJobTitle.Text = row["JobTitle"].Value.ToString();
txtDepartment.Text = row["Department"].Value.ToString();
break;
}
FYI, you can use LINQ extensions to do this:
var tbl = ds.Tables[0].AsEnumerable();
return tbl.Where(p => p["first_name"] == fname).FirstOrDefault();
Edit: To select all matching rows from the DataTable:
var results = from row in tbl.AsEnumerable()
where row["first_name"] == fname
select row;
Related
private void btnCheck_Click(object send, EventArgs ex)
{
string querytxt = #"SELECT Count(itemno) FROM Items WHERE itemno = #itemno";
SqlConnection cnn = new SqlConnection(#"Data Source=PC80978273\SQLEXPRESS;Initial Catalog=Inventory;User ID=sa;Password=Rmdj1q2w3e!");
SqlCommand cmd = new SqlCommand(querytxt, cnn);
cnn.Open();
cmd.Parameters.AddWithValue("#itemno", txtName.Text);
int result = (int)cmd.ExecuteScalar();
if (result > 0)
{
btnDelete.Enabled = true;
SqlConnection conn = new SqlConnection(#"Data Source=PC80978273\SQLEXPRESS;Initial Catalog=Inventory;User ID=sa;Password=Rmdj1q2w3e!");
SqlCommand cmnd = new SqlCommand("SELECT itemno, categ, name, quant, price FROM Items ", conn);
conn.Open();
SqlDataReader dr = cmnd.ExecuteReader();
if (dr.Read())
{
label6.Text = dr.GetValue(0).ToString();
label1.Text = dr.GetValue(1).ToString();
label2.Text = dr.GetValue(2).ToString();
label3.Text = dr.GetValue(3).ToString();
label4.Text = dr.GetValue(4).ToString();
}
txtName.Clear();
txtName.Enabled = false;
btnCheck.Enabled = false;
}
else
MessageBox.Show("No data found!");
cnn.Close();
}
I have 2 rows of data in the database with "itemno" as my primary key. The textbox "txtName.Text" is the value of the item number(itemno) in the database. The value of the labels will depend on the input of txtName.Text. However, when i click the "Check" button, it only displays the first row. I have tried enterring the value of "itemno" on the textbox but the labels still display the values of the first row. How would I fix this to correct the display of the labels depending on the "itemno" that was entered on the textbox?
You should amend your query use where clause to get the desired row on base of value entered in textbox like:
int val = Convert.ToInt32(txtName.Text);
string strQuery = "SELECT itemno, categ, name, quant, price FROM Items Where itemno = " + val;
SqlCommand cmnd = new SqlCommand(strQuery, conn);
My code:
DataTable dt = new DataTable();
mySqlDataAdapter.Fill(dt);
int socot = dt.Rows.Count;
for (int i = 0; i < socot; i++)
{
String dn = dt.Rows[i][1].ToString();
String gduan = "SELECT tennha FROM duannha WHERE id=#id";
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = gduan;
cmd.Parameters.AddWithValue("#id", dn);
String gtennha = cmd.ExecuteScalar().ToString();
dt.Rows[i][1] = gtennha;
}
When I run code, I received an error. Please help me fix it.
Expected Type as Int32
If gtennha contains a number, you can parse it to an int. With more safeguards:
var gtennha = cmd.ExecuteScalar();
try
{
if(gtennha != null)
dt.Rows[i][1] = int.Parse(gtennha.ToString());
else
Console.WriteLine("Error: Query didn't return a result.");
}
catch(FormatException ex)
{
Console.WriteLine("Error: Couldn't parse 'gtennha' to a number.");
/* more error handling */
}
Parse string to int
DataTable dt = new DataTable();
mySqlDataAdapter.Fill(dt);
int socot = dt.Rows.Count;
for (int i = 0; i < socot; i++)
{
String dn = dt.Rows[i][1].ToString();
String gduan = "SELECT tennha FROM duannha WHERE id=#id";
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = gduan;
cmd.Parameters.AddWithValue("#id", dn);
String gtennha = cmd.ExecuteScalar().ToString();
int a;
int.TryParse(gtennha, out a);
dt.Rows[i][1] = a;
}
Update
if gtennha always start with VIOFFICE or a word something like that then use this way split string
DataTable dt = new DataTable();
mySqlDataAdapter.Fill(dt);
int socot = dt.Rows.Count;
for (int i = 0; i < socot; i++)
{
String dn = dt.Rows[i][1].ToString();
String gduan = "SELECT tennha FROM duannha WHERE id=#id";
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = gduan;
cmd.Parameters.AddWithValue("#id", dn);
String gtennha = cmd.ExecuteScalar().ToString();
int a;
int.TryParse(gtennha.Split(' ')[1], out a);
dt.Rows[i][1] = a;
}
I think you have choosen the wrong column to assign the return value of your ExecuteScalar query. From your error message it is clear that the return value is a string "VI BUILDING 29BD" (or something like that) and you are trying to assing that value to the same column dt.Rows[i][1] that you have used as the source for the ID parameter. This of course cannot be correct.
So you need to identify what is the column that you want to assign the return value of the ExecuteScalar and take extra care on handling that return value that could be NULL if there is no match on the WHERE clause
DataTable dt = new DataTable();
mySqlDataAdapter.Fill(dt);
int socot = dt.Rows.Count;
for (int i = 0; i < socot; i++)
{
String dn = dt.Rows[i][1].ToString();
String gduan = "SELECT tennha FROM duannha WHERE id=#id";
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = gduan;
cmd.Parameters.AddWithValue("#id", dn);
object result = cmd.ExecuteScalar();
// SUPPOSE THAT YOU WANT TO ASSIGN AT COLUMN 2 NOT STILL AT COLUMN 1
if(result != null)
dt.Rows[i][2] = gtennha;
}
I want to show a DataGridView with Compte Name and total sum of Recette and Depense per month and year.
I have a DateTimePicker customized with month an year.Image of the Winforms and the error
Example : if I select date = 11/2015 (November 2015), it will show like that
Compte Total
BTK 633,000
Biat 987,888
Caisse 988,875
and if I select date = 06/2016 (Jun 2016), it will show like that
Compte Total
BTK 0
Biat 653,256
Caisse 88,145
My Code :
public partial class ComptesMois : Form
{
SqlConnection conn;
SqlCommand comm;
SqlDataReader dreader;
string connstring = "Data Source=.;Initial Catalog=Tresorerie;Integrated Security=True";
public ComptesMois()
{
InitializeComponent();
//Set Columns Count
DataGridViewCompteMois.ColumnCount = 2;
//Hide the last blank line
DataGridViewCompteMois.AllowUserToAddRows = false;
//Add Columns
DataGridViewCompteMois.Columns[0].Name = "NomCom";
DataGridViewCompteMois.Columns[0].HeaderText = "Nom de Compte";
DataGridViewCompteMois.Columns[0].DataPropertyName = "NomCom";
DataGridViewCompteMois.Columns[0].Width = 100;
//Add Columns
DataGridViewCompteMois.Columns[1].Name = "Total";
DataGridViewCompteMois.Columns[1].HeaderText = "Total";
DataGridViewCompteMois.Columns[1].DataPropertyName = "Total";
DataGridViewCompteMois.Columns[1].Width = 100;
this.BindGrid();
CompteMoisdateTimePicker.Format = DateTimePickerFormat.Custom;
CompteMoisdateTimePicker.CustomFormat = "MM yyyy";
//CompteMoisdateTimePicker.ShowUpDown = true; // to prevent the calendar from being displayed
}
private void BindGrid()
{
DataGridViewCompteMois.DataSource = null;
using (SqlConnection con = new SqlConnection(connstring))
{
using (SqlCommand cmd = new SqlCommand("select DISTINCT c.NomCom from Tresorerie t join Compte c on t.IdCom=c.IdCom", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
DataGridViewCompteMois.DataSource = dt;
}
}
}
}
}
private void DataGridViewCompteMois_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
string month = CompteMoisdateTimePicker.Value.Month.ToString();
string year = CompteMoisdateTimePicker.Value.Year.ToString();
//select * from < table > where month(searchDate) = Month_from_box and Year(searchDate) = Year_from_box
// select sum(recette + depence) from Tresorerie where
String total;
for (int i = 0; i < DataGridViewCompteMois.Rows.Count; i++)
{
conn = new SqlConnection(connstring);
conn.Open();
String NomCompteDataGrid = Convert.ToString(DataGridViewCompteMois.Rows[i].Cells[0].Value);
String IdCompteValue = "select IdCom from Compte where NomCom='" + NomCompteDataGrid + "'";
comm = new SqlCommand(IdCompteValue, conn);
int IdComValue = Convert.ToInt32(comm.ExecuteScalar());
conn.Close();
using (SqlConnection con = new SqlConnection(connstring))
{
using (SqlCommand cmd = new SqlCommand("select sum(Recette + Depense) as Total from Tresorerie where IdCom=#IdCom GROUP BY Recette,Depense", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#IdCom", IdComValue);
con.Open();
total = Convert.ToString(cmd.ExecuteNonQuery());
con.Close();
}
}
DataGridViewCompteMois.Rows[i].Cells[1].Value = total;
}
}
}
but there is an error, the result show me -1 for every Compte
Update 1: Thanks to #Soner_Gönül, I modify the query statement, and I tested it on sql and it works, but the problem when I add the result to the grid cell, it shows empty, but I try to show it with messgae box and it works, my code :
String total;
private void CompteMoisdateTimePicker_ValueChanged(object sender, EventArgs e)
{
string month = CompteMoisdateTimePicker.Value.Month.ToString();
string year = CompteMoisdateTimePicker.Value.Year.ToString();
for (int i = 0; i < DataGridViewCompteMois.Rows.Count; i++)
{
conn = new SqlConnection(connstring);
conn.Open();
String NomCompteDataGrid = Convert.ToString(DataGridViewCompteMois.Rows[i].Cells[0].Value);
String IdCompteValue = "select IdCom from Compte where NomCom='" + NomCompteDataGrid + "'";
comm = new SqlCommand(IdCompteValue, conn);
int IdComValue = Convert.ToInt32(comm.ExecuteScalar());
conn.Close();
using (SqlConnection con = new SqlConnection(connstring))
{
using (SqlCommand cmd = new SqlCommand("select SUM( Depense + Recette ) from Tresorerie where IdCom=#IdCom and MONTH(DateTre) = #MONTH AND YEAR(DateTre) = #YEAR GROUP BY IdCom", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#IdCom", IdComValue);
cmd.Parameters.AddWithValue("#MONTH", month);
cmd.Parameters.AddWithValue("#YEAR", year);
con.Open();
total = Convert.ToString(cmd.ExecuteScalar());
con.Close();
}
}
DataGridViewCompteMois.Rows[i].Cells["Total"].Value = total;
//MessageBox.Show(total.ToString());
}
}
Update Solution: look I have a problem which cell selected, this code works
private void CompteMoisdateTimePicker_ValueChanged(object sender, EventArgs e)
{
string month = CompteMoisdateTimePicker.Value.Month.ToString();
string year = CompteMoisdateTimePicker.Value.Year.ToString();
for (int i = 0; i < DataGridViewCompteMois.Rows.Count; i++)
{
conn = new SqlConnection(connstring);
conn.Open();
String NomCompteDataGrid = Convert.ToString(DataGridViewCompteMois.Rows[i].Cells[1].Value);
String IdCompteValue = "select IdCom from Compte where NomCom='" + NomCompteDataGrid + "'";
comm = new SqlCommand(IdCompteValue, conn);
int IdComValue = Convert.ToInt32(comm.ExecuteScalar());
conn.Close();
using (SqlConnection con = new SqlConnection(connstring))
{
using (SqlCommand cmd = new SqlCommand("select SUM( Depense + Recette ) from Tresorerie where IdCom=#IdCom and MONTH(DateTre) = #MONTH AND YEAR(DateTre) = #YEAR GROUP BY IdCom", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#IdCom", IdComValue);
cmd.Parameters.AddWithValue("#MONTH", month);
cmd.Parameters.AddWithValue("#YEAR", year);
con.Open();
//MessageBox.Show(Convert.ToString(cmd.ExecuteScalar()));
DataGridViewCompteMois.Rows[i].Cells["Total"].Value = Convert.ToString(cmd.ExecuteScalar());
con.Close();
}
}
}
}
I think the problem is using ExecuteNonQuery with a SELECT statement since;
For UPDATE, INSERT, and DELETE statements, the return value is the
number of rows affected by the command. When a trigger exists on a
table being inserted or updated, the return value includes the number
of rows affected by both the insert or update operation and the number
of rows affected by the trigger or triggers. For all other types of
statements, the return value is -1.
Looks like you need to use ExecuteScalar as well to get total of your Recette + Depense columns.
I am fetching records of users and binding it to gridview. I want to show the number of results returned like "15 results found". I used RecordsAffected but I think it wont work with select statement. Any alternate way?
using (SqlConnection con = new SqlConnection(strCon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select name, city, number where age between " + from.Text + "AND " + to.Text;
cmd.Connection = con;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
reader.Close();
usersgrid.DataSource = cmd.ExecuteReader();
usersgrid.DataBind();
con.Close();
}
else
{
result.Visible = true;
}
}
}
Now I want to show number of rows returned on a label.
int affectedRows = cmd.ExecuteNonQuery();
that would work for you insted of cmd.ExecuteReader();
another alternative will be to get rowcount of the usersGrid control
int Count = usersGrid.Rows.Count-((usersGrid.PageCount-1) * usersGrid.PageSize);
I can retrieve data from the database and it works now, but only on the first line (both description and code are correct and based on the database).
On the second line, the description is not based on the database, however it display the description for the first line, even though the code for first and second line are different. How do I fix that?
Here is some code:
private void UpdateDatas()
{
int codeValue = 0;
OleDbDataReader dReader;
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
OleDbCommand cmd = new OleDbCommand(
"SELECT [Description], [Price] FROM [Data] WHERE [Code]=#Code", conn);
cmd.Parameters.Add("Code", System.Data.OleDb.OleDbType.Integer);
cmd.Parameters.Add("Code", System.Data.OleDb.OleDbType.Integer);
if (int.TryParse(this.textBoxCodeContainer[0][0].Text, out codeValue))
{
cmd.Parameters["Code"].Value = codeValue;
}
else if (int.TryParse(this.textBoxCodeContainer[0][1].Text, out codeValue))
{
cmd.Parameters["Code"].Value = codeValue;
}
else
{
MessageBox.Show("Error");
}
dReader = cmd.ExecuteReader();
while (dReader.Read())
{
if (textBoxCodeContainer[0][0].TextLength != 0)
{
this.textBoxDescContainer[0][0].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[0][0].Text = dReader["Price"].ToString();
}
if (textBoxCodeContainer[0][1].TextLength != 0)
{
this.textBoxDescContainer[0][1].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[0][1].Text = dReader["Price"].ToString();
}
}
dReader.Close();
conn.Close();
}
Here is the image:
Here is the image of the database:
That's because you processes first record twice in your loop, for both text boxes. Try this as a quick fix:
int index = 0;
while (dReader.Read())
{
if (textBoxCodeContainer[0][index].TextLength != 0)
{
this.textBoxDescContainer[0][index].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[0][index].Text = dReader["Price"].ToString();
}
index += 1;
}
The second problem, is that you add two values for one parameter (Code) in your query, so the result of the select will contain only one row. You should you the "IN" SQL keyword. The second quick fix would concern your query:
var query = "SELECT [Description], [Price] FROM [Data] WHERE [Code] IN (";
if (int.TryParse(this.textBoxCodeContainer[0][0].Text, out codeValue))
{
query = query + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][1].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
query = query + ")";
OleDbCommand cmd = new OleDbCommand(query, conn);
dReader = cmd.ExecuteReader();
How to parametrize the query with the "IN" clause is another problem - this is just a quick fix to make this work.