here is two of my 'Ders' items(bottom listbox)
it gets items but i cant display them, two output should come from query so query is correct.Something must be wrong in DisplayMember but i couldn't figure it out for 2 hours.
here is the data that i receive from query
and here is my code
private void kryptonListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
bolumsilbutton.Enabled = true;
bolumuduzenlebutton.Enabled = true;
bolumupbutton.Enabled = true;
bolumdownbutton.Enabled = true;
derseklebutton.Enabled = true;
derslistbox.Enabled = true;
if (Connection.DBPath == null)
{
//burada bölüm ismine göre veri çekilecek(veritabanı olmadan!)
}
else
{
try
{
OleDbConnection con = new OleDbConnection();
string query;
con = Connection.GetConnection();
con.Open();
query = "SELECT Ders.ders_id, Ders.ders_ismi FROM Ders INNER JOIN (Bölüm INNER JOIN Bölüm_ders ON Bölüm.bolum_id = Bölüm_ders.bolum_id.Value) ON Ders.ders_id = Bölüm_ders.ders_id WHERE (((Bölüm.bolum_id)=" + bolumlerlistbox.SelectedValue.ToString() + "))";
OleDbDataAdapter da = new OleDbDataAdapter(query, con);
DataSet ds = new DataSet();
da.Fill(ds, "Ders");
Connection.bolumlerform.derslistbox.DisplayMember = "Ders.ders_ismi";
Connection.bolumlerform.derslistbox.ValueMember = "Ders.ders_id";
Connection.bolumlerform.derslistbox.DataSource = ds.Tables["Ders"];
con.Close();
}
catch (OleDbException ex)
{
MessageBox.Show("Veritabanına bağlanırken hata oluştu !" + ex.Message);
}
}
}
I have found the solution if someone is having trouble to find it. I have changed the query this
SELECT Ders.ders_id, Ders.ders_ismi FROM... to this
SELECT Ders.ders_id as ders_id, Ders.ders_ismi as ders_ismi FROM ...
and of course changed the display member and value member to this
Connection.bolumlerform.derslistbox.DisplayMember = "ders_ismi"; Connection.bolumlerform.derslistbox.ValueMember = "ders_id";
Related
Recently i developed a search function, but i want when a user inputs something on the textbox the datagridview to not go blank but instead to show the data that it already has and when the result is found than only show the result. Because now when i type anything on the search textbox the dgv immediately goes blank.
Here is my code:
private void txtBarkod_TextChanged(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(txtBarkod.Text)) {
resetTxTboxes();
}
MySqlConnection connection = Connection.prevzemiKonekcija();
try {
connection.Open();
MySqlCommand command;
MySqlDataAdapter adapter;
DataTable tabela;
string query = "SELECT * FROM artikli WHERE barcode like '%" + txtBarkod.Text + "%'";
command = new MySqlCommand(query, connection);
adapter = new MySqlDataAdapter(command);
tabela = new DataTable();
adapter.Fill(tabela);
dataGridView1.DataSource = tabela;
if (txtBarkod.Text == "") {
ShowDgV();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
connection.Close();
}
}
Reset/Rebind the datasource of your datagridview only if you found something in your db.
if(tabela.Rows.Count > 0)
{
dataGridView1.DataSource = tabela;
}
I am having trouble with my SQL statement to pass the value from my dropdownlist select to my gridview. I tested my SQL statement Serve Management Studio, with a specific date, and it works, but it isn't working with select value from my Dropdownlist. How would I pass the value to the Gridview? Thank you for help, I am new student to the asp.net world.
Image of web application:
Image of My DATABASE:
public void RefreshDay()
{
SqlConnection conn = new SqlConnection(#"data source =.\sqlexpress; integrated security = true; database = DBdentist");
SqlDataAdapter da = null;
DataSet ds = null;
DataTable dt = null;
string sqlsel = "SELECT Distinct patient.patientID, day from patient, patientreservation where patient.patientID = patientreservation.patientID";
try
{
da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(sqlsel, conn);
ds = new DataSet();
da.Fill(ds, "myDay");
dt = ds.Tables["myDay"];
DropDownListDay.DataSource = dt;
DropDownListDay.DataTextField = "day";
DropDownListDay.DataValueField = "patientID";
DropDownListDay.DataBind();
DropDownListDay.Items.Insert(0, "Select Day");
}
catch (Exception ex)
{
LabelDay.Text = ex.Message;
}
finally
{
conn.Close();
}
}
protected void DropDownListDay_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownListDay.SelectedIndex != 0)
{
SqlConnection conn = new SqlConnection(#"data source =.\sqlexpress; integrated security = true; database = DbDentist");
SqlDataAdapter da = null;
DataSet ds = null;
DataTable dt = null;
string sqlsel = "SELECT patientreservation.patientID, patient.firstname, patient.lastname, patientreservation.day, patientreservation.hour, treatment.treatment FROM((patientreservation INNER JOIN patient ON patientreservation.patientID = patient.patientID) INNER JOIN treatment ON patientreservation.treatmentID = treatment.treatmentID) WHERE patientreservation.day = " + DropDownListDay.SelectedValue + "";
try
{
da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(sqlsel, conn);
ds = new DataSet();
da.Fill(ds, "myDay");
dt = ds.Tables["myDay"];
GridViewDay.DataSource = dt;
GridViewDay.DataBind();
}
catch (Exception ex)
{
LabelDay.Text = ex.Message;
}
finally
{
conn.Close();
}
}
else
{
LabelDay.Text = "You choose None:";
}
}
}
}
You can simply use this:
WHERE patientreservation.day = '" + DropDownListDay.Text.ToString() + "'";
Thanks for the help. I tried everything
DropDownListDay.DataTextField = "day";
DropDownListDay.DataValueField = "day"
helped. I was also having some problem with my gridview. I added up deleting it and making a new, somehow that help.
The configuration of your dropdown is
DropDownListDay.DataTextField = "day";
DropDownListDay.DataValueField = "patientID";
but you need the day as a value if you want to filter with the current selected value
DropDownListDay.DataTextField = "day";
DropDownListDay.DataValueField = "day";
SELECT patientreservation.patientID, patient.firstname, patient.lastname, patientreservation.day, patientreservation.hour, treatment.treatment FROM((patientreservation INNER JOIN patient ON patientreservation.patientID = patient.patientID) INNER JOIN treatment ON patientreservation.treatmentID = treatment.treatmentID) WHERE **patientreservation.day** = " + DropDownListDay.**SelectedValue** + "";
Or you can try with WHERE **patientreservation.day** = " + DropDownListDay.**SelectedText** + "";
The dropdownlist is not triggering the event. Try to put this AutoPostBack="true" in your asp dropdownlist tag.
I have fetched the data from SQL server to datagridview but I don't know how to change the cell value. I have to change the fetched value 1 and 0 to available and unavailable. here is my code for fetching data ... please help.
private void btnsearch_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server = 192.168.100.6;Database=sms;UID=sa;Password=1234;");
SqlCommand cmd = new SqlCommand("Select id as 'Book ID',name as 'Name' , status as 'Status' from book where Name = #name", con);
cmd.Parameters.AddWithValue("#name", txtFirstName.Text);
try
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
BindingSource bsource = new BindingSource();
bsource.DataSource = dt;
dataGridView1.DataSource = bsource;
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
// chage_value();
dataGridView1.Show();
}
}
Please find below answer
private void btnsearch_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server = 192.168.100.6;Database=sms;UID=sa;Password=1234;");
string sSql=#"Select id as 'Book ID',name as 'Name' ,
Case when status=0 then 'unavailable' else 'available '
End as 'Status' from
book where Name ='"+txtFirstName.Text +"'"
SqlCommand cmd = new SqlCommand(sSql, con);
try
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
// chage_value();
dataGridView1.Show();
}
}
First of all, try to store your queries in variables. This will help you in the long run. Also, it is good practise to check whether you are connected or not before trying to send a query away to the server. It is important to remeber that when you fetch data from your server, it will most likely be seen as a string, so if you want to compare it as a number, you need to convert it first.
What you could do is something similar to what i've written below. You count the amount of answers your query returns, then loop through them and check whether they are 0 or 1. Then just replace the value with Avaliable or Unavaliable.
if (dbCon.IsConnect()){
MySqlCommand idCmd = new MySqlCommand("Select * from " + da.DataGridView1.Text, dbCon.Connection);
using (MySqlDataReader reader = idCmd.ExecuteReader()){
// List<string> stringArray = new List<string>(); // you could use this string array to compare them, if you like this approach more.
while (reader.Read()){
var checkStatus= reader["Status"].ToString();
Console.WriteLine("Status: " + checkStatus.Split(' ').Count()); //checks how many items you've got.
foreach (var item in checkStatus.Split(' ').Select(x => x.Trim()).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray()){
var item2 = 0.0; // your 0 or 1 for avaliable or unavaliable..
try{
item2 = double.Parse(item.ToString());
if(strcmp(item2,'0') == 1){ //assuming you only have 0's and 1's.
item2 = "unavaliable";
}else{
item2 = "avaliable";
}
}
catch (Exception){
//do what you want
}
Console.WriteLine("item: " + item2);
}
}
dbCon.Close();
}
}
return //what you want;
}
I think my code is correct but why error syntax near 'po_no' check my code please. What is the problem with my code with this kind of error? Do I need to JOIN or two queries? I just want to display the two table using inner join
try
{
if (cb_po_search.Text == "")
{
MessageBox.Show("Please Enter to Search!");
}
else
{
string strPRSconn = ConfigurationManager.ConnectionStrings["POSdb"].ConnectionString;
SqlConnection sc = new SqlConnection(strPRSconn);
sc.Open();
string strQry = "SELECT dbo.POMain.po_no, dbo.POMain.issuing_month, dbo.POMain.supplier, dbo.POMain.model, dbo.POMain.category, dbo.POMain.req_number, dbo.POMain.shipment, dbo.POMain.production_month, dbo.POMain.req_time_arrival, dbo.POMain.req_department, dbo.POMain.lead_time, dbo.POMain.order_desc, dbo.POMain.date_emailed, dbo.POMain.date_confirmed, dbo.POMain.date_recieved, dbo.POMain.assumed_arrival, dbo.Shipping.invoice, dbo.Shipping.loading_date, dbo.Shipping.etd, dbo.Shipping.eta_manila, dbo.Shipping.eta_tstech, dbo.Shipping.ata_tstech, dbo.Shipping.shipping_status, dbo.Shipping.remarks FROM dbo.POMain INNER JOIN dbo.Shipping ON dbo.POMain.po_no = dbo.Shipping.po_noWHERE po_no= '" + cb_po_search.Text + "'";
SqlCommand scmd = new SqlCommand(strQry, sc);
SqlDataAdapter da = new SqlDataAdapter(strQry, sc);
DataTable dt = new DataTable();
SqlDataReader dr = scmd.ExecuteReader();
while (dr.Read())
{
//purchase order
tb_ponumber2.Text = (dr["po_no"].ToString());
tb_reqnumber2.Text = (dr["req_number"].ToString());
cb_supplier2.Text = (dr["supplier"].ToString());
cb_model2.Text = (dr["model"].ToString());
cb_category2.Text = (dr["category"].ToString());
cb_shipment2.Text = (dr["shipment"].ToString());
ta_description2.Text = (dr["order_desc"].ToString());
tb_leadtime2.Text = (dr["lead_time"].ToString());
tb_request2.Text = (dr["req_department"].ToString());
dt_time_arrival2.Value = DateTime.Parse(dr["req_time_arrival"].ToString());
dt_arrival2.Value = DateTime.Parse(dr["assumed_arrival"].ToString());
dt_confirmed2.Value = DateTime.Parse(dr["date_confirmed"].ToString());
dt_email2.Value = DateTime.Parse(dr["date_emailed"].ToString());
dt_production_month2.Value = DateTime.Parse(dr["production_month"].ToString());
dt_recieve2.Value = DateTime.Parse(dr["date_recieved"].ToString());
dt_issuing_month2.Value = DateTime.Parse(dr["issuing_month"].ToString());
}
sc.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Your code is asking for an SQL Injection, use parametized queries instead with SqlParameter class.
Edit. Your query have a missing equals sign at the end. Things that woudn't happen using parametized queries ;-)
http://www.csharp-station.com/Tutorial/AdoDotNet/lesson06
I need some help to complete this. I have searched and tried several ways but is not enetring in my head yet. It is not homework! I am a self learner.
I managed to populate a grid selecting the table from a dropdown:
private void radDropDownList1_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
{
if (radDropDownList1.SelectedIndex > 0)
{
radGridView1.Visible = true;
label8.Text = radDropDownList1.SelectedValue.ToString();
DataTable dt = new DataTable();
var selectedTable = radDropDownList1.SelectedValue; //Pass in the table name
string query = #"SELECT * FROM " + selectedTable;
using (var cn = new SqlConnection(connString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand(query, cn);
using (var da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
catch (SqlException ex)
{
//MessageBox.Show(ex.StackTrace);
}
}
radGridView1.DataSource = dt;
}
Now I am trying to write the event to update the sql table using the grid as datasource:
private void radGridView1_CellEndEdit(object sender, Telerik.WinControls.UI.GridViewCellEventArgs e)
{
DataTable dt = (DataTable)radGridView1.DataSource;
DataSet ds = new DataSet();
ds.Tables[0] = dt;
try
{
//**I am lost here!**
}
catch
{
}
}
Could you please help? How can I now update the sql table?
I don't really like the way you are managing the updates but... this code here will send an update statement:
using (var cn = new SqlConnection(connString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand("UPDATE YourTable SET Column = #Parm1 WHERE Col = #Parm2", cn);
var parm1 = cmd.CreateParameter("Parm1");
parm1.Value = "SomeValue";
var parm2 = cmd.CreateParameter("Parm2");
parm2.Value = "SomeOtherValue";
cmd.Parameters.Add(parm1);
cmd.Parameters.Add(parm2);
int rowsAffected = cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
//MessageBox.Show(ex.StackTrace);
}
}