I'm trying to load a SQL row of numbers into multiple text boxes. Basically the row contains numbers separated by ";". How can I get it so that each number when separated by ";" is in their own textbox?
SqlConnection conn = new SqlConnection("Data Source=LAURA-PC;Initial Catalog=Sudoku;Integrated Security=True");
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "Select puzzle from Puzzle";
command.CommandType = CommandType.Text;
SqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
textBox1.Text = reader.GetValue(0).ToString();
textBox2?
textbox3?
}
conn.Close();
Assuming that you have the same amount of (or fewer) numbers than TextBoxes , you could put your TextBoxes into an array and use the following code:
...
SqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
string[] tokens = reader.GetString(0).Split(';');
for(int i = 0; i < tokens.Length; i++)
{
textBoxes[i].Text = tokens[i];
}
}
...
Assuming the puzzle column has the semi-colon delimited numbers:
...
SqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
string[] tokens = ((string)reader[0]).Split(';');
textBox1.Text = tokens[0];
textBox2.Text = tokens[1];
// etc...
}
...
Related
When filling a combobox with data in database, the first row in database was missing.
con = new SqlConnection(cs.connetionString);
con.Open();
Sql = "SELECT * FROM ItemRate";
command = new SqlCommand(Sql, con);
SqlDataReader reader = command.ExecuteReader();
reader.Read();
while (reader.Read())
{
string cat = reader["RateOfInt"].ToString();
comboBox4.Items.Add(cat);
}
Calling reader.Read() advances one row, so the first time you call it before the while loop it already lands on the first row, but then you call it again in the while condition, so it advances to the second row, just remove the call before the condition.
con = new SqlConnection(cs.connetionString);
con.Open();
Sql = "SELECT * FROM ItemRate";
command = new SqlCommand(Sql, con);
SqlDataReader reader = command.ExecuteReader();
// remove this line
// reader.Read();
while (reader.Read())
{
string cat = reader["RateOfInt"].ToString();
comboBox4.Items.Add(cat);
}
Edit: Here is the example from the Docs
con = new SqlConnection(cs.connetionString);
con.Open();
Sql = "SELECT * FROM ItemRate";
command = new SqlCommand(Sql, con);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string cat = reader["RateOfInt"].ToString();
comboBox4.Items.Add(cat);
}
I have Oracle data like this:
The table is named KETERANGAN and I want those data in textBox1. Not just one row but all rows. This my code used OracleDataReader
OracleCommand cmd = new OracleCommand();
OracleDataReader dr;
cmd.CommandText = #"SELECT NOTES FROM KETERANGAN";
cmd.Connection = koneksidb.con;
dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = dr["NOTES"].toString();
}
dr.Close();
I get: You're Cool.
I want: You're Cool, Amazing, Wonderful
use += instead of = which will append the result. you are currently replacing it.
OracleCommand cmd = new OracleCommand();
OracleDataReader dr;
cmd.CommandText = #"SELECT NOTES FROM KETERANGAN";
cmd.Connection = koneksidb.con;
dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text += dr["NOTES"].toString() + ",";
}
dr.Close();
It could be done like this:
// wrap IDisposable into using
using (OracleCommand cmd = new OracleCommand()) {
cmd.Connection = koneksidb.con;
// Make SQL readable
cmd.CommandText =
#"SELECT Notes
FROM Keterangan";
// wrap IDisposable into using; do not close manually - dr.Close()
using (OracleDataReader dr = cmd.ExecuteReader()) {
// do not append string in loop - use SringBuilder
StringBuilder sb = new StringBuilder();
while (dr.Read()) {
if (sb.Length > 0) // <- do not put delimiter before the very first item
sb.Append(", "); // <- do you want a delimiter? Say, comma?
// ".ToString()" provides debug info, use Convert.ToString() instead
sb.Append(Convert.ToString(dr.GetValue(0)));
}
// Assign data once in order to prevent re-painting (and blinking)
textBox1.Text = sb.ToString();
}
}
Hope, the comments inside the routine explain the code enough.
Safe and optimized solution...
var notesBuilder = new StringBuilder();
const string SQL = #"SELECT NOTES FROM KETERANGAN";
using (var cmd = new OracleCommand(SQL, koneksidb.con))
{
using (OracleDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
notesBuilder.Append(dr["NOTES"]);
notesBuilder.AppendLine(",");
}
}
}
textBox1.Text = notesBuilder.ToString();
Or you can set the Multiline property on your textbox to true and use
textBox1.Lines.Add(dr["NOTES"].toString());
I want to retrieve value /miejsca/, but I don't how it works. For example please show me how selecting value define as variable or how to show it in textbox.
At this point I recieve "System.Data.SqlClient.SqlDataReader" in textbox.
SqlDataReader reader;
cn.Open();
cmd.CommandText = ("SELECT miejsca FROM oferty WHERE oferty.idoferty = #rezerw");
cmd.Parameters.AddWithValue("#rezerw", rezerw);
cmd.CommandType = CommandType.Text;
cmd.Connection = cn;
reader = cmd.ExecuteReader().Read
string rs = Convert.ToString(reader);
TextBox1.Text = rs;//at this point i recieve "System.Data.SqlClient.SqlDataReader" in textbox
cn.Close();
If you are reading a single row and a single column: just use ExecuteScalar():
string rs = (string)cmd.ExecuteScalar();
But to answer your question, the normal usage is:
using(var reader = cmd.ExecuteReader())
{
while(reader.Read())
{
// read a row, for example:
string foo = reader.GetString(0);
Console.WriteLine(foo);
}
}
I want to insert MySqlDataReader read value into an array.but I get the exception "Index was outside the bounds of the array". Here is my code,
string[] a = new string[1000];
string myconstring = "SERVER=localhost;" + "DATABASE=alicosms;" + "UID=root;" + "PASSWORD=;";
MySqlConnection mycon = new MySqlConnection(myconstring);
string sql = "SELECT flag FROM sms_data_bankasia group by flag";
MySqlCommand comd = mycon.CreateCommand();
comd.CommandText = sql;
mycon.Open();
MySqlDataReader dtr = comd.ExecuteReader();
count = 0;
int i = 0;
while (dtr.Read())
{
a[i] = dtr.GetValue(i).ToString();
i++;
}
What can I do.Any one can help me?
Try cleaning your code a little and use a dynamically resizing List<T> to which you can add elements:
var result = new List<string>();
var myconstring = "SERVER=localhost;DATABASE=alicosms;UID=root;PASSWORD=;";
using (var con = new MySqlConnection(myconstring))
using (var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "SELECT flag FROM sms_data_bankasia group by flag";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
result.Add(reader.GetString(reader.GetOrdinal("flag")));
}
}
}
string[] a = result.ToArray();
This looks suspicious to me:
a[i] = dtr.GetValue(i).ToString();
That means you're fetching column 0 of row 0, column 1 of row 1, column 2 of row 2 etc... but you've only got a single column ("flag").
I suspect you meant:
a[i] = dtr.GetValue(0).ToString();
That will still fail if there are more than 1000 rows though - it would be better to use a List<string>:
List<string> data = new List<string>();
while (dtr.Read())
{
data.Add(dtr.GetValue(0).ToString()); // Or call GetString
}
Does anybody know, how to show databases in C#? I know thats possible by executing a sql command show databases, but i dont know how to configure reader. Anybody please help me.
EDIT: I found a solution:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MySqlConnection con = new MySqlConnection(this.constr);
MySqlCommand cmd = con.CreateCommand();
cmd.CommandText = "show databases";
try
{
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string row = "";
for (int i = 0; i < reader.FieldCount; i++)
row += reader.GetValue(i).ToString();
listBox1.Items.Add(row);
}
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Number.ToString());
MessageBox.Show(ex.Message);
}
}
string myConnectionString = "SERVER=localhost;UID='root';" + "PASSWORD='root';";
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SHOW DATABASES;";
MySqlDataReader Reader;
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
string row = "";
for (int i = 0; i < Reader.FieldCount; i++)
row += Reader.GetValue(i).ToString() + ", ";
comboBox1.Items.Add(row);
}
connection.Close();
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand com = new SqlCommand ("show databases",conn);
conn.Open();
SqlDataReader reader = com.ExecuteReader();
DataTable dt = new DataTable;
dt.Load(reader);
DataRows[] rows = dt.Rows;
Think you can then view the data rows
That said, if you already have the connection string, there's no reason not to open MSqlServer or whatever and view it from there...