Timeout error when trying to connect to remote address database - c#

I keep getting timeout error, only a few times my code works. I was reading in this forum that I had to use "using" before the mysql. So I tried adding it, but still no luck. Maybe I'm using it wrong? Left my last connection to database without "using" so you guys can see how it was at first
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 MySql.Data.MySqlClient;
namespace WindowsFormsApplication4
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
FillCombo();
}
void FillCombo()
{
string dbcon = "SERVER=IP;DATABASE=mudiw_test;UID=mudiw_test;PASSWORD=PASS";
string Query = "select * from mudiw_test.Registration ;";
using (MySqlConnection conDatabase = new MySqlConnection(dbcon))
{
using (MySqlCommand cmDatabase = new MySqlCommand(Query, conDatabase))
{
MySqlDataReader myReader;
try
{
conDatabase.Open();
myReader = cmDatabase.ExecuteReader();
while (myReader.Read())
{
string sName = myReader.GetString("Name");
comboBox1.Items.Add(sName);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string dbcon = "SERVER=IP;DATABASE=mudiw_test;UID=mudiw_test;PASSWORD=PASS";
string Query = "select * from mudiw_test.Registration where Name='" + comboBox1.Text + "' ;";
using (MySqlConnection conDatabase = new MySqlConnection(dbcon))
{
using (MySqlCommand cmDatabase = new MySqlCommand(Query, conDatabase))
{
MySqlDataReader myReader;
try
{
conDatabase.Open();
myReader = cmDatabase.ExecuteReader();
while (myReader.Read())
{
string sName = myReader.GetString("Name");
string sId = myReader.GetString("ID");
string sEmail = myReader.GetString("Email");
string sAddress = myReader.GetString("Address");
string sPhone = myReader.GetString("Phone");
string sVisits = myReader.GetString("Visits");
name.Text = sName;
id.Text = sId;
email.Text = sEmail;
address.Text = sAddress;
phone.Text = sPhone;
address.Text = sAddress;
visits.Text = sVisits;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox2.SelectedItem == "Mantenimiento")
{
int value;
if (Int32.TryParse(visits.Text, out value))
{
if (value < 3)
{
price.Text = "150";
total.Text = "150";
discount.Text = "0%";
}
else if (value >= 3 && value <= 6)
{
price.Text = "150";
total.Text = "127.50";
discount.Text = "15%";
}
else if (value >= 7)
{
price.Text = "150";
total.Text = "112.50";
discount.Text = "25%";
}
}
}
}
private void tabPage1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string dbcon = "SERVER=IP;DATABASE=mudiw_test;UID=mudiw_test;PASSWORD=PASS";
string Query = "insert into mudiw_test.Registration (Name,ID,Email,Address,Phone) values('" + this.name.Text + "','" + this.id.Text + "','" + this.email.Text + "','" + this.address.Text + "','" + this.phone.Text + "');";
MySqlConnection conDatabase = new MySqlConnection(dbcon);
MySqlCommand cmDatabase = new MySqlCommand(Query, conDatabase);
MySqlDataReader myReader;
try
{
conDatabase.Open();
myReader = cmDatabase.ExecuteReader();
MessageBox.Show("Saved");
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}

The timeout won't be related to the using statement; wrapping the connection in using simply ensures that the connection is disposed when you are done with it. A timeout likely means that you have network connectivity issues between your machine and the database or you've supplied the wrong server name.

Related

How to display full name from combobox to textbox separated by space

I have connection with local database. I wanted full name from (in this case) combobox4 to textbox textbox. It displays this value but without separation with space. For example from combobox4 "S BOX" in textbox is only "S". I tried with textBox4.Text = string.Join(" ", parts[1]); but i couldn't work. I share my code:
Insertstatus.cs
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 MySql.Data.MySqlClient;
namespace KontrolaBazaDanych
{
public partial class InsertStatus : Form
{
string Zlecenie_wykonane;
string Zlecenie_rozpoczete;
MySqlConnection connection;
MySqlCommand command;
MySqlDataReader dr;
Form1 frm1 = (Form1)Application.OpenForms["Form1"];
public InsertStatus()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;username=root;password=");
string InsertQuery = "INSERT INTO projekt1.status_zl(ID_ZLECENIA, ID_PRACOWNIKA, ID_MODULU, ID_PROJEKTU, ILOSC_PRODUKTOW, DATA_ROZPOCZECIA, DATA_ZAKONCZENIA, ZLECENIE_WYKONANE, ZLECENIE_ROZPOCZETE) VALUES('" + textBox7.Text + "','" + textBox9.Text + "','" + textBox8.Text + "','"+ textBox10.Text +"','" + numericUpDown4.Value.ToString() + "','" + dateTimePicker1.Value.ToString("yyyy-MM-dd HH:mm:ss") + "','" + dateTimePicker2.Value.ToString("yyyy-MM-dd HH:mm:ss") + "','" + Zlecenie_wykonane + "','" + Zlecenie_rozpoczete + "')";
connection.Open();
MySqlCommand command = new MySqlCommand(InsertQuery, connection);
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("Dane są dodane.");
}
else
{
MessageBox.Show("Błąd.");
}
frm1.loaddata4();
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
textBox6.Clear();
textBox7.Clear();
textBox8.Clear();
textBox9.Clear();
numericUpDown4.Value = 0;
dateTimePicker1.Value = DateTime.Now;
dateTimePicker2.Value = DateTime.Now;
checkBox1.Checked = false;
checkBox2.Checked = false;
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
Zlecenie_wykonane = "1";
Zlecenie_rozpoczete = "0";
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
Zlecenie_wykonane = "0";
Zlecenie_rozpoczete = "1";
}
private void InsertStatus_Load(object sender, EventArgs e)
{
connection = new MySqlConnection();
connection.ConnectionString = "datasource=localhost;port=3306;username=root;password=";
connection.Open();
string selectQuery2 = "SELECT * FROM projekt1.pracownicy";
MySqlCommand command2 = new MySqlCommand(selectQuery2, connection);
MySqlDataReader reader2 = command2.ExecuteReader();
while (reader2.Read())
{
comboBox1.Items.Add(reader2.GetString("ID_PRACOWNIKA") + " " + reader2.GetString("IMIE") + " " + reader2.GetString("NAZWISKO"));
}
connection.Close();
connection.Open();
string selectQuery3 = "SELECT * FROM projekt1.moduly";
MySqlCommand command3 = new MySqlCommand(selectQuery3, connection);
MySqlDataReader reader3 = command3.ExecuteReader();
while (reader3.Read())
{
comboBox2.Items.Add(reader3.GetString("NAZWA"));
}
connection.Close();
connection.Open();
string selectQuery4 = "SELECT * FROM projekt1.zlecenia";
MySqlCommand command4 = new MySqlCommand(selectQuery4, connection);
MySqlDataReader reader4 = command4.ExecuteReader();
while (reader4.Read())
{
comboBox3.Items.Add(reader4.GetString("NUMER_ZLECENIA"));
}
connection.Close();
connection.Open();
string selectQuery5 = "SELECT * FROM projekt1.projekty";
MySqlCommand command5 = new MySqlCommand(selectQuery5, connection);
MySqlDataReader reader5 = command5.ExecuteReader();
while (reader5.Read())
{
comboBox4.Items.Add(reader5.GetString("ID") + " " + reader5.GetString("NAZWA_PROJEKTU"));
}
connection.Close();
textBox1.Enabled = false;
textBox2.Enabled = false;
textBox3.Enabled = false;
textBox3.Enabled = false;
textBox4.Enabled = false;
textBox5.Enabled = false;
textBox6.Enabled = false;
textBox7.Enabled = false;
textBox8.Enabled = false;
textBox9.Enabled = false;
textBox10.Enabled = false;
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
command = new MySqlCommand("SELECT * FROM projekt1.moduly WHERE NAZWA='"+ comboBox2.Text +"'", connection);
connection.Open();
command.ExecuteNonQuery();
MySqlDataReader dr;
dr = command.ExecuteReader();
while (dr.Read())
{
string nazwa = (string)dr["NAZWA"].ToString();
textBox3.Text = nazwa;
string id_modulu = (string)dr["ID_MODULU"].ToString();
textBox8.Text = id_modulu;
}
connection.Close();
}
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
command = new MySqlCommand("SELECT * FROM projekt1.zlecenia WHERE NUMER_ZLECENIA='" + comboBox3.Text+"'", connection);
connection.Open();
command.ExecuteNonQuery();
dr = command.ExecuteReader();
while (dr.Read())
{
string opis = (string)dr["OPIS_ZLECENIA"].ToString();
textBox5.Text = opis;
string numer = (string)dr["NUMER_ZLECENIA"].ToString();
textBox6.Text = numer;
string status_zl = (string)dr["ID_ZLECENIA"].ToString();
textBox7.Text = status_zl;
}
connection.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex != -1)
{
string[] parts = comboBox1.Items[comboBox1.SelectedIndex].ToString().Split(' ');
textBox9.Text = parts[0];
textBox1.Text = parts[1];
textBox2.Text = parts[2];
}
}
private void comboBox4_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox4.SelectedIndex != -1)
{
string[] parts = comboBox4.Items[comboBox4.SelectedIndex].ToString().Split(' ');
textBox10.Text = parts[0];
textBox4.Text = string.Join(" ", parts[1]);
}
}
}
}
I can't find any solution which may be effective. It's about string.Join construction or should create public class? Has someone idea how to solve it or explain by example code? Greetings.
Okey i've got that solution which i can do that and it's for now solved:
private void comboBox4_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox4.SelectedIndex != -1)
{
string[] parts = comboBox4.Items[comboBox4.SelectedIndex].ToString().Split(' ');
textBox10.Text = parts[0];
textBox4.Text = comboBox4.Text.Remove(0,2).Trim();
}

Insert Data from a textbox into a database . c# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Hello stack overflow you are my only hope, Its my first question here. I'm having problem with inserting things into a database from textboxes i searched throught it i tried everything it just doesnt work. Here is my code ->
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace E_BANK
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_save_Click(object sender, EventArgs e)
{
//objekti per konektim me DBne
SqlConnection conn = new SqlConnection(#"Data Source=desktop-ndocu0t\sqlexpress;Initial Catalog=MetinShop;Integrated Security=True");
conn.Open();
using (SqlCommand command = conn.CreateCommand())
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string accref = tb_accref.Text;
int deposit = Convert.ToInt32(tb_depamount.Text);
int psID = Convert.ToInt32(tb_personalID.Text);
string query = "INSERT INTO Bank1(accref, deposit, psID) " +
"Values('" + accref + "', '" + deposit + "', '" + psID + "')";
}
}
}
//mbylle lidhjen me DB
conn.Close();
MessageBox.Show("Transition Updatet Sucessfully");
}
private void btn_reset_Click(object sender, EventArgs e)
{
tb_accref.Text = "";
tb_depamount.Text = "";
tb_personalID.Text = "";
lblamount.Text = "0";
}
private void btn_exit_Click(object sender, EventArgs e)
{
Close();
}
}
}
Try this way
private void btn_save_Click(object sender, EventArgs e)
{
using (SqlConnection sqlConn = new SqlConnection(#"Data Source=desktop-ndocu0t\sqlexpress;Initial Catalog=MetinShop;Integrated Security=True"))
{
using (SqlCommand sqlComm = new SqlCommand("INSERT INTO Bank1 (accref, deposit, psID) VALUES (#accref, #deposit, #psID)", sqlConn))
{
if (sqlComm.Connection.State == ConnectionState.Closed)
sqlComm.Connection.Open();
string accref = tb_accref.Text;
int deposit = Convert.ToInt32(tb_depamount.Text);
int psID = Convert.ToInt32(tb_personalID.Text);
sqlComm.Parameters.AddWithValue("#accref", accref);
sqlComm.Parameters.AddWithValue("#deposit", deposit);
sqlComm.Parameters.AddWithValue("#psID", psID);
sqlComm.ExecuteNonQuery();
MessageBox.Show("Transition Updatet Sucessfully");
}
}
}
You need to actually run the INSERT command. Check out the ExecuteNonQuery method on the SqlCommand class.
EXECUTE Command missing
private void btn_save_Click(object sender, EventArgs e)
{
//objekti per konektim me DBne
SqlConnection conn = new SqlConnection(#"Data Source=desktop-ndocu0t\sqlexpress;Initial Catalog=MetinShop;Integrated Security=True");
conn.Open();
string accref = tb_accref.Text;
int deposit = Convert.ToInt32(tb_depamount.Text);
int psID = Convert.ToInt32(tb_personalID.Text);
//try all fields are string
string query = "INSERT INTO Bank1(accref, deposit, psID) Values('" + accref + "', '" + deposit + "', '" + psID + "')";
//try last fields are numeric
//string query = "INSERT INTO Bank1(accref, deposit, psID) Values('" + accref + "', " + deposit + ", " + psID + ")";
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandText = query;
command.ExecuteNonQuery()
//mbylle lidhjen me DB
conn.Close();
MessageBox.Show("Transition Updatet Sucessfully");
}
private void btn_reset_Click(object sender, EventArgs e)
{
tb_accref.Text = "0";
tb_depamount.Text = "0";
tb_personalID.Text = "0";
lblamount.Text = "0";
}
private void btn_exit_Click(object sender, EventArgs e)
{
Close();
}

c# Auto populate result of a textboxt.Text from database, base on 2 different combo box

namespace Training
{
public partial class AddingNewData : Form
{
public AddingNewData()
{
InitializeComponent();
fillcombo1();
fillcombo2();
autopopulatedays();
}
string original_city, destination_city;
void fillcombo1()
{
string constring = "datasource=localhost;port=3306;username=root;password=root";
string Query = "SELECT * FROM itemdelivery.fee GROUP BY orig_city;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string storig = myReader.GetString("orig_city");
comboBox1.Items.Add(storig);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void fillcombo2()
{
string constring = "datasource=localhost;port=3306;username=root;password=root";
string Query = "SELECT * FROM itemdelivery.fee GROUP BY dest_city;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string stdest = myReader.GetString("dest_city");
comboBox2.Items.Add(stdest);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
original_city = comboBox1.Text;
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
destination_city = comboBox2.Text;
}
private void txt_deliverytime_TextChanged(object sender, EventArgs e)
{
}
void autopopulatedays()
{
string constring = "datasource=localhost;port=3306;username=root;password=root";
string Query = "SELECT `del_time` FROM `itemdelivery.fee` WHERE `orig_city` = #oc AND `dest_city`= #dc";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
try
{
conDataBase.Open();
cmdDataBase.Parameters.AddWithValue("#oc", original_city);
cmdDataBase.Parameters.AddWithValue("#dc", destination_city);
object result = cmdDataBase.ExecuteScalar();
if (result != null)
txt_deliverytime.Text = result.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
So, I have 2 combo boxes, After selecting 2 of them, I put the values in original_city and destination_city as string, using comboBox1_SelectedIndexChanged and comboBox2_SelectedIndexChanged.
Then on method autopopulatedays(), I tried to auto-populate the txt_deliverytime.Text with a single integer value by matching the value of original_city and destination_city on the database using
that query.
But, so why I failed? The only error I got is "No database selected" which is weird for me, and when I select 2 combo box choices, the
txt_deliverytime.Text doesn't get auto-populated.
========================================================================
// UPDATE VERSION
// Connected to database, and ignoring the code before(above),
// This code only meant to auto-populate txt_deliverytime.Text when
// combobox1.selectitem and combobox2.selectitem
// Why it's still wrong?.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
original_city = comboBox1.SelectedItem.ToString();
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
destination_city = comboBox2.SelectedItem.ToString();
// if the combobox1 is not empty and combobox2 is also not empty, then run this code
if (comboBox1.SelectedItem.ToString() != null)
{
string constring = "datasource=localhost;port=3306;username=root;password=root";
string Query = "SELECT del_time FROM itemdelivery.fee WHERE orig_city='" + original_city + "' AND dest_city='" + destination_city + "';";
// if I run this query on MySQL, it will show only a column name del_time with only a single row,
// thus only show a value, I want to get that value to txt_deliverytime.Text
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
conDataBase.Open();
string getValue = cmdDataBase.ExecuteScalar().ToString();
if (getValue != null)
{
txt_deliverytime.Text = getValue.ToString();
// meant to change it here, but seems not successful
}
conDataBase.Close();
}
}
First use a valid ConnectionString:
Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;
Pwd=myPassword;
Then I suppose this is not your actual code, because there is a missing curly bracket
public partial class AddingNewData : Form
{
public AddingNewData()
{
InitializeComponent();
fillcombo1();
fillcombo2();
autopopulatedays();
}
And finally you should `autopopulatedays' when comboBox1 or comboBox2 selected item change, not only when you fill the combos.
I solved the code above into the code like this below =
namespace Training
{
public partial class AddingNewData : Form
{
public AddingNewData()
{
InitializeComponent();
fillcombo1();
fillcombo2();
}
string original_city, destination_city;
void fillcombo1()
{
string constring = "datasource=localhost;port=3306;username=root;password=root";
string Query = "SELECT * FROM itemdelivery.fee GROUP BY orig_city;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string storig = myReader.GetString("orig_city");
comboBox1.Items.Add(storig);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void fillcombo2()
{
// EMPTY
}
// just some improvement on query
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
original_city = comboBox1.SelectedItem.ToString();
string constring = "datasource=localhost;port=3306;username=root;password=root";
string Query = "SELECT DISTINCT dest_city FROM itemdelivery.fee WHERE orig_city = '" + original_city + "' GROUP BY destination_city ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string stdest = myReader.GetString("dest_city");
comboBox2.Items.Add(stdest);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
// this is where I solved the problem
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
destination_city = comboBox2.SelectedItem.ToString();
string constring = "datasource=localhost;port=3306;username=root;password=root";
string Query = "SELECT del_time FROM itemdelivery.fee WHERE orig_city ='" + original_city + "' AND dest_city ='" + destination_city + "';";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
try
{
conDataBase.Open();
var result = cmdDataBase.ExecuteScalar();
if (result != null)
{
txt_deliverytime.Text = result.ToString();
}
conDataBase.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void txt_deliverytime_TextChanged(object sender, EventArgs e)
{
}
}

Link listBox with Database and show values in textBox if select index in listBox. C#

That works on displaying the items from database in the listbox but i need that if i select a value in the listbox it displays information about that person back to the textboxes. Thats the thing that i can't get to work.
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 MySql.Data.MySqlClient;
namespace program
{
public partial class Form8 : Form
{
public Form8()
{
InitializeComponent();
fill_listbox();
}
void fill_listbox()
{
string constring = "datasource=sql2.freesqldatabase.com;port=3306;username=sql217040;password=xxxxx";
string Query = "select * from sql217040.fakedata ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string id1 = myReader.GetString("id");
string name1 = myReader.GetString("name");
string surname1 = myReader.GetString("surname");
listBox1.Items.Add(id1 + ' ' + name1 + ' ' + surname1);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = "datasource=sql2.freesqldatabase.com;port=3306;username=sql217040;password=xxxxx";
string Query = "select * from sql217040.fakedata where name='" + listBox1.Text + "' ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string sname = myReader.GetString("name");
string ssurname = myReader.GetString("surname");
string sphone = myReader.GetString("phone");
textBox1.Text = sname;
textBox2.Text = ssurname;
//telephone.Text = sphone;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
ideally i would change your listbox to datagridview and change your method like this
void fill_listbox()
{
try
{
string constring = "datasource=sql2.freesqldatabase.com;port=3306;username=sql217040;password=xxxxx";
string Query = "select * from sql217040.fakedata ;";
using(MySqlConnection conDataBase = new MySqlConnection(constring))
{
conDataBase.Open();
using (SqlDataAdapter a = new SqlDataAdapter(Query, conDataBase))
{
DataTable t = new DataTable();
a.Fill(t);
// Render data onto the screen
dataGridView1.DataSource = t; // <-- datagridview1 is the gridview i have added
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
and read the values like this from cell double click event of gridview
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
string name = dataGridView1.Rows[e.RowIndex].Cells["columnname"].Value.ToString();
}
Why don't you use DataSet instead of DataReader.
Just add all items into the listbox and get the selected item from DataSet by the listbox selectedItemIndex. This will save the the extra query when listbox selected index changed.

problem getting my data from access 2003 db into c# (dbReader.GetString error)

[got a bit further so its updated]
Hello There, i really hope you are able to help me!
Now the first part of my code does work, and I do get my report numbers out in my combobox, and i'm able to write that number to a lbl. now I need to take that number and get the rest of my data from my Access 2003 database, and drop them in a string (my output). ( I dont really want all the data loaded into my mem when i open the program, so i belive only getting the [Rapport nr] until i choose one, where I will load the data into the string and save it there for now) :)
my problem is that this wont work!
output = dbReader.GetString(dbReader.GetOrdinal("Dato")).ToString();
OBS: my error is now that it says i dont have any data in my rows or coloums
my code is as follows:
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.Collections;
using System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private string aktuelRapportNR = "";
string output = "";
private string connectionName = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=semcqdjh-access 2007.mdb;"
+ "Jet OLEDB:Database Password=;";
public Form1()
{
InitializeComponent();
#region Indlæsning af combobox, med rapport numre
OleDbConnection Myconnection = null;
OleDbDataReader dbReader = null;
Myconnection = new OleDbConnection(connectionName);
Myconnection.Open();
OleDbCommand cmd = Myconnection.CreateCommand();
cmd.CommandText = "SELECT [Rapport nr] FROM AVR";
dbReader = cmd.ExecuteReader();
int rapportNR;
while (dbReader.Read())
{
rapportNR = (int)dbReader.GetInt32(dbReader.GetOrdinal("Rapport nr"));
comboBox1.Items.Add(rapportNR);
}
dbReader.Close();
Myconnection.Close();
#endregion
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
aktuelRapportNR = comboBox1.SelectedItem.ToString();
lblAktuelRapportNR.Text = aktuelRapportNR;
OleDbConnection Myconnection = null;
OleDbDataReader dbReader = null;
Myconnection = new OleDbConnection(connectionName);
Myconnection.Open();
OleDbCommand cmd = Myconnection.CreateCommand();
cmd.CommandText = "SELECT [Dato] FROM AVR WHERE [Rapport nr] =" + aktuelRapportNR;
dbReader = cmd.ExecuteReader();
try
{
output = dbReader.GetString(dbReader.GetOrdinal("Dato")).ToString();
}
catch (Exception)
{
output = "fejl eller tom";
}
dbReader.Close();
Myconnection.Close();
label1.Text = output;
}
private void btnExport_Click(object sender, EventArgs e)
{
}
}
}
i figured this out :D after a break i went back to this and tried to see if there where enother method i could use and there was :P i figured by the error that it was properly something about the types so insted of taking one out and trying to work around that i took the hole row out and placed it in a object array :P by using GetValues in the dbReader i got it to work, so i can now move on :D for those who might be interested! here is my code :P its not pretty but it works :P i allso took in som try catch just to make sure i check for errors and getting a friendly respons on that :)
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.Collections;
using System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private string aktuelRapportNR = "";
string output;
private string connectionName = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=semcqdjh-access 2007.mdb;"
+ "Jet OLEDB:Database Password=;";
public Form1()
{
InitializeComponent();
#region Indlæsning af combobox, med rapport numre
try
{
OleDbConnection Myconnection = null;
OleDbDataReader dbReader = null;
Myconnection = new OleDbConnection(connectionName);
Myconnection.Open();
OleDbCommand cmd = Myconnection.CreateCommand();
cmd.CommandText = "SELECT [Rapport nr] FROM AVR";
dbReader = cmd.ExecuteReader();
int rapportNR;
while (dbReader.Read())
{
rapportNR = (int)dbReader.GetInt32(dbReader.GetOrdinal("Rapport nr"));
comboBox1.Items.Add(rapportNR);
}
dbReader.Close();
Myconnection.Close();
txtStatus.Text = "Indlæsning Fuldført! Vælg venligst en rapport";
}
catch (Exception)
{
txtStatus.Text = "Indlæsning Fejlet!";
}
#endregion
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
aktuelRapportNR = comboBox1.SelectedItem.ToString();
lblAktuelRapportNR.Text = aktuelRapportNR;
txtStatus.Text = "Du har valgt rapport nr.: " + aktuelRapportNR + "! Klik på export";
}
private void btnExport_Click(object sender, EventArgs e)
{
try
{
OleDbConnection Myconnection = null;
OleDbDataReader dbReader = null;
Myconnection = new OleDbConnection(connectionName);
Myconnection.Open();
OleDbCommand cmd = Myconnection.CreateCommand();
cmd.CommandText = "SELECT * FROM AVR WHERE [Rapport nr] =" + aktuelRapportNR;
dbReader = cmd.ExecuteReader();
object[] liste = new object[dbReader.FieldCount];
if (dbReader.Read() == true)
{
int NumberOfColums = dbReader.GetValues(liste);
for (int i = 0; i < NumberOfColums; i++)
{
output += "|" + liste[i].ToString();
}
}
dbReader.Close();
Myconnection.Close();
txtStatus.Text = "Export Lykkes! Luk programmet!";
}
catch (Exception)
{
txtStatus.Text = "Export Fejlet!";
}
}
}
}

Categories

Resources