I have been wondering for quiet long time how can I set my SqlDataReader to fill column "pocet" in my datagridview "dtg_ksluzby". I thought that my code should look something like this:
SqlCommand novyprikaz2 = new SqlCommand("SELECT pocet FROM klisluz WHERE id='"+vyberradek+"'",spojeni); // I also have column "pocet" in table klisluz, vyberradek is string which selectrs id number
spojeni.Open();
SqlDataReader precti2 = novyprikaz2.ExecuteReader();
if (precti2.Read())
{
dtg_ksluzby.Columns["pocet"]; // this part I need to improve to fill
}
Would you please help me to improve my code?
Thanks so much in advance.
Edit for trippino:
In "klisluz" which is in the table that includes columns
(id,akce,subkey,text,pocet). I need to:
select * from klisluz where subkey = '"+vyberradek+"'
Take column pocet and fill it into dtg_ksluzby where i find the text is similar in column "text" in dtg_ksluzby
I hope my description is understandabla, sorry for my weak english.
Do not use string concatenation to build sql commands, (to avoid Sql Injection and parsing problem)
using(SqlConnection spojeni = new SqlConnection(conString))
using(SqlCommand novyprikaz2 = new SqlCommand("SELECT pocet FROM klisluz " +
"WHERE id = #id",spojeni);
{
novyprikaz2.Parameters.AddWithValue("#id", vyberradek);
spojeni.Open();
using(SqlDataAdapter da = new SqlDataAdapter(novyprikaz2))
{
DataTable dt = new DataTable();
da.Fill(dt);
dtg_ksluzby.DataSource = dt;
}
}
Use a DataAdapter to load your data from database and pass this DataAdapter instance to the DataSource of your DataGridView
Use something like this:
for (int i = 0; i < dtg_ksluzby.Rows.Count; i++)
{
var row = dtg_ksluzby.Rows[i];
using(var novyprikaz2 = new SqlCommand("SELECT pocet FROM klisluz WHERE text LIKE #t AND subkey=#s", spojeni))
{
novyprikaz2.Parameters.AddWithValue("#t", row.Cells["text"].Value.ToString());
novyprikaz2.Parameters.AddWithValue("#s", vyberradek);
spojeni.Open();
SqlDataReader precti2 = novyprikaz2.ExecuteReader();
if (precti2.Read())
{
row.Cells["pocet"].Value = precti2["pocet"];
}
}
}
Related
I am using C# to create a windows form.
I am trying to set a condition statement for a particular value that is retrieved from my database by the onclick of a button. The datatype of the column is 'integer'.
Below is my code:
string checkquantity = "SELECT `inventory_item`.`Item_Quantity_Available`FROM `inventory_item` , `patient`, `out_treatment`WHERE `inventory_item`.`Item_ID` = `out_treatment`.`Inventory_ID`AND `patient`.`Patient_ID` = `out_treatment`.`Patient_ID`AND `out_treatment`.`Patient_ID`= '" + pid + "' ";
MySqlCommand selectout = new MySqlCommand(checkquantity, connect);
MySqlDataAdapter selectdata = new MySqlDataAdapter(checkquantity, connect);
DataTable selecttable = new DataTable();
selectdata.Fill(selecttable);
DataSet ds = new DataSet();
selectdata.Fill(selecttable);
selectdata.Fill(ds);
int i = ds.Tables[0].Rows.Count;
if ( i <= 0)
{
MessageBox.Show("Out of Stock");
}
I'm new with c#.
I don't think the int i = ds.Tables[0].Rows.Count; is the right way.
Any help is much appreciated.
First of all, like #Flydog57 said, you should not concatenate your sql query. The best way is to use parameters, for example:
string checkquantity = "SELECT i.Item_Quantity_Available " +
" FROM inventory_item i JOIN out_treatment t ON i.Item_Id = t.Inventory_ID " +
" JOIN patient p ON t.Patient_ID = p.PatiendID " +
" WHERE t.Patient_ID = #Patiend_ID";
MySqlCommand selectout = new MySqlCommand(checkquantity, connect);
// set the parameter value
selectout.Parameters.AddWithValue("#Patiend_ID", patient_id_value);
MySqlDataReader rdr = cmd.ExecuteReader();
if (rdr.Read())
{
if ((int)rdr["Item_Quantity_Available"] == 0)
MessageBox.Show("Out of Stock");
}
In second place, you could use a MySqlDataReader to verify that Item_Quantity_Available is equal to 0, like in the previous example. Otherwise, If you just wants to verify if there is data, the condition could be something like that:
if (!rdr.Read())
{
MessageBox.Show("Out of Stock");
}
The third improvemente is to join tables with the join clause.
This is my second question here in StackOverflow and this is where im stuck
i want to loop every value in a multiline textbox and pass it as query criteria then fill my DataGridView with the result (multiple results).
The problem is. that i cannot pass more than 1 value from the textbox. i can execute correctly the query but its not looping correctly as it only shows the result of the first value in my data grid and i want the data(result) from every line in the textbox
my code is
for (int i = 0; i < textBox1.Lines.Length; i++)
{
Connect();
OracleCommand cmd = new OracleCommand();
OracleDataAdapter adapter = new OracleDataAdapter();
DataTable dt = new DataTable();
cmd = new OracleCommand(OraSql + OraSql2 + orasql3 + OraSql4, con);
adapter = new OracleDataAdapter(cmd);
cmd.ExecuteNonQuery();
adapter.Fill(dt);
foreach (DataRow row in dt.Rows)
{
dataGridView1.Rows.Add
(
row[0].ToString(),
row[1].ToString(),
row[2].ToString(),
row[3].ToString(),
row[4].ToString(),
row[5].ToString()
);
}
}
i hope that i explained myself correctly here
Thank you!
this is my query
string OraSql = #"SELECT r.ixkitl ""Parent Part Number"",
r.ixlitm ""Component Part Number"",
i.imdsc1 ""Description"",
SUM((r.ixqnty/10000)) ""Qty per Harness"",
To_date(r.ixefff+1900000, 'YYYYDDD') ""Effective From Date"",
To_date(r.ixefft+1900000, 'YYYYDDD') ""Effective Thru Date"",
r.ixtbm ""Bill Type"",
r.ixmmcu ""Branch Plt""
FROM proddta.f3002 r,
proddta.f4101 i";
string OraSql2 = #"
WHERE (i.imlitm IN '" + textBoxX1.Text.ToString() + "'AND i.imitm = r.ixkit)";
string orasql3 = #"
AND (r.ixmmcu = ' 3320' AND r.ixtbm = 'M ')";
string OraSql4 = #"
AND r.ixefff <= (to_char(SYSDATE, 'YYYYDDD')-1900000)
AND r.ixefft >= (to_char(SYSDATE, 'YYYYDDD')-1900000)
GROUP BY r.ixkitl,
r.ixlitm,
r.ixqnty,
r.ixtbm,
r.ixmmcu,
r.ixefff,
r.ixefft,
i.imdsc1
ORDER BY r.ixkitl,
r.ixlitm";
I'm new to C#. I'm having a difficult time displaying my Access data in a DataTable. Here is the code:
try
{
reader.Read();
for (int i = 0; i < 16; i++)
{
if (selectedCourse == reader["CourseName"].ToString())
{
match = true;
}
else
{
match = false;
}
}
if (match == true)
{
tabControl.SelectedTab = tabPage1; // opens results page
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\...454_Database.accdb";
DataTable results = new DataTable();
using (OleDbConnection conn = new OleDbConnection(connString))
{
OleDbCommand cmd = new OleDbCommand("Select c.PeriodID, c.CourseName, c.Teacher, t.Room"
+ "FROM Courses c JOIN Teacher t ON t.TeacherID = c.TeacherID"
+ "WHERE [CourseName] ='" + cboxClass.Text + "'", conn);
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(results);
dataTblResults.DataSource = results;
I can tell the data is being compared to the db and it correctly determines if the query has results or not. However, when there are results, they do not get displayed on the data table. Is it because it doesn't know which columns correspond to the columns in the data table?
Thanks in advance!
How is your datagrid configured?
Try setting: (before setting the DataSource)
dataTblResults.AutoGenerateColumns = true;
dataTblResults.DockStyle.Fill = DockStyle.Fill;
Try using a Dataset first. Then turn it to a datatable
DataSet ds = new DataSet();
adapter.fill(ds)
if (ds.Tables[0].Rows.Count >= 1)
{
results = ds.Tables[0];
}
dataTblResults.DataSource = results;
I dont think this is what you are looking for but maybe it'll bring you closer to the answer
I am using multi column in combo box. So,I would like to display a database table like this photo.
I tried the below coding but I get only the table date without the table borders.
private void affich()
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
req = "select id_amort_fiscal+''+amort_fiscal as combined from amortissementFiscal;";
SqlCommand sql = new SqlCommand(req, connection);
dr = new SqlDataAdapter(req, connection);
dr.Fill(ds, "amortissementFiscal");
multiColumnComboBox1.DataSource = ds.Tables["amortissementFiscal"];
multiColumnComboBox1.DisplayMember="combined";
multiColumnComboBox1.ValueMember = "combined";
connection.Close();
return;
}
this is what I get as a result:
any Help please and thanks :D
Is this third party control?
Anyway your query is showing you are only picking 1 column. Try adding more columns in query.
private void affich()
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
// *******************
// See the new_column2, new_column3 in the below query, replace them
// with your own columns
// ********************
req = "select id_amort_fiscal+''+amort_fiscal as combined, new_column2, new_column3 from amortissementFiscal;";
SqlCommand sql = new SqlCommand(req, connection);
dr = new SqlDataAdapter(req, connection);
dr.Fill(ds, "amortissementFiscal");
multiColumnComboBox1.DataSource = ds.Tables["amortissementFiscal"];
multiColumnComboBox1.DisplayMember="combined";
multiColumnComboBox1.ValueMember = "combined";
connection.Close();
return;
}
Make sure you have assigned ColumnToDisplay property to your MultiColumnCombobox.
multiColumnComboBox1.ColumnsToDisplay = new String[] {"Combinded Fiscal", "First Name"};
This will bind your column data into particular column. To display the proper column header, I preferred to specify alias in your sql query and try to add more columns in your query.
req = "select (id_amort_fiscal+''+amort_fiscal) As [Combinded Fiscal], FName As [First Name] from amortissementFiscal;";
I have this code
SqlConnection conn = Database.GetConnection();
//not sure why doing this bit (bit between this comment and next
//SqlDataAdapter adapter = new SqlDataAdapter("Select * From CarType", conn);
DataSet DataSetRentals2 = new DataSet("CustomerSQLTable");
DataTable table = new DataTable("CustomerSQLTable"); //you can name it
DataTable table2 = new DataTable("CarRental");
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
adapter.SelectCommand = new SqlCommand("SELECT * FROM Customer", conn);
conn.Open();
///this might brake the code
///
adapter.Fill(DataSetRentals2,"CustomerSQLTable");
adapter.SelectCommand = new SqlCommand("SELECT * FROM CarRental", conn);
adapter.Fill(DataSetRentals2, "CarRental");
adapter.Fill(DataSetRentals2, "CarRental");
}
CustomerGrid.DataSource = DataSetRentals2;
CustomerGrid.DataMember = "CustomerSQLTable";
CarRGrid.DataSource = DataSetRentals2.Tables["CarRental"];
CarRGrid.DataMember = "CarRental";
the teacher gave me this code to link them in a relationship so that when i click on one customer number in one data grid and for it to only return corresponding records in the other.
DataRowView selectedRow =
(DataRowView)CustomerGrid.SelectedRows[0].DataBoundItem;
DataSetRentals2.Tables["CarRental"].DefaultView.RowFilter =
"CustomerNo = " + selectedRow.Row["CustomerNo"].ToString();.
so what i think i need to do is to name the columns in the dataset. But i have no idea how to do this. I'm sure there must be a way an I'm sure you guy's can easily tell me it. Thank you in advanced.
dataTable.Columns[0].ColumnName = "MyColumnName";
Your columns will already have names. They are supplied by the database.
I would guess that your issue is with this line. If this isn't it please describe what you're expecting to happen, vs what is actually happening so that we may assist you better.
CarRGrid.DataSource = DataSetRentals2.Tables["CarRental"];
Which should probably be
CarRGrid.DataSource = DataSetRentals2;