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();
}
Related
I am making a school project and i need to put text input (name and gender) into a database. This database (the names and genders) then have to be shown in a listbox. The code i have at the moment is put below, how can i make it work? Thanks in advance!
private void Form1_Load(object sender, EventArgs e)
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM
Persoon", connection))
{
connection.Open();
DataTable PersoonTable = new DataTable();
adapter.Fill(PersoonTable);
lb_gebruikers.DisplayMember = "Naam";
lb_gebruikers.ValueMember = "Id";
lb_gebruikers.DataSource = PersoonTable;
}
}
private void button1_Click(object sender, EventArgs e)
{
string naam = tb_naam.Text;
string geslacht = tb_geslacht.Text;
Persoon nieuwpersoon = new Persoon(naam, geslacht);
personen.Add(nieuwpersoon);
foreach (var Persoon in personen)
{
lb_gebruikers.Items.Add("Naam: " + nieuwpersoon.Naam +
"Geslacht: " + nieuwpersoon.Geslacht);
}
}
As i understand you just have to add a insert between button1.click and addToList process.
private void btnSave_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection("Server =.;Database=People; Integrated Security = true");
con.Open();
SqlCommand cmd = new SqlCommand(); // you can define commandText and connection in SqlCommand(defineArea);
cmd.Connection = con; // like; cmd = newSqlCommand("Insert into...",con);
string name = txtName.Text;
string gender = txtGender.Text;
cmd.CommandText = "Insert into Person(Name,Gender)values('" + name + "','" + gender + "')";
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
lstBxPerson.Items.Add(name + " - " + gender);
MessageBox.Show("Save Success!");
}
catch (Exception ex)
{
MessageBox.Show("Exception : "+ex);
}
}
Database Name : People
Table Name : Person
All Parts Image :
I have a problem when click on submit button. the data still insert into database even though there is an invalid data.
public partial class surveyCreate : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
private string lblTextMessage;
protected void Page_Load(object sender, EventArgs e)
{
btnSubmitSurvey.Attributes.Add("onclick", "return PostPage();");
List<string> keys = Request.Form.AllKeys.Where(key => key.Contains("txtDynamic")).ToList();
int i = 1;
foreach (string key in keys)
{
this.CreateTextBox("txtDynamic" + i);
i++;
}
if (!IsPostBack)
{
int a_unit = 0;
string username = (string)Session["Username"];
string query5 = "SELECT * FROM tblAdmin WHERE a_uname='" + username + "'";
con.Open();
SqlCommand cmd5 = new SqlCommand(query5, con);
SqlDataReader dr5 = cmd5.ExecuteReader();
if (dr5.Read())
{
a_unit = Convert.ToInt32(dr5["a_unit"]);
}
dr5.Close();
con.Close();
string queryA = "";
string queryB = "";
string queryC = "";
queryA = "SELECT * FROM tblUnit WHERE u_master = " + a_unit;
queryB = "SELECT * FROM tblProject ";
queryC = "SELECT * FROM tblSurveyTemplate where st_template = " + a_unit;
BindDropDownList(ddlunit, queryA, "u_name", "u_id", "SELECT UNIT");
//BindDropDownList(project, queryB, "pro_name", "pro_id", "SELECT PROJECT");
BindDropDownList(ddlTemplate, queryC, "st_name", "st_id", "SELECT TEMPLATE");
ddlproject.Enabled = false;
}
}
private void BindDropDownList(DropDownList ddl, string query, string text, string value, string defaultText)
{
// string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString();
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = conn;
conn.Open();
ddl.DataSource = cmd.ExecuteReader();
ddl.DataTextField = text;
ddl.DataValueField = value;
ddl.DataBind();
conn.Close();
}
}
ddl.Items.Insert(0, new ListItem(defaultText, "0"));
}
protected void unit_SelectedIndexChanged(Object sender, EventArgs e)
{
ddlproject.Enabled = true;
int u_id = int.Parse(ddlunit.SelectedItem.Value);
string query = "Select pro_id, pro_name from tblProject WHERE u_id=" + u_id;
BindDropDownList(ddlproject, query, "pro_name", "pro_id", "SELECT PROJECT");
}
protected void ddlTemplate_SelectedIndexChanged(Object sender, EventArgs e)
{
int st_id = int.Parse(ddlTemplate.SelectedItem.Value);
SqlDataSourceQuestions.SelectCommand = "SELECT sq_id, sq_question FROM tblSurveyQuestions WHERE st_id=" + st_id;
string query = "SELECT * FROM tblSurveyTemplate WHERE st_id=" + st_id;
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
LabelComment.Text = dr["st_comment"].ToString();
LabelIntro.Text = dr["st_intro"].ToString();
}
dr.Close();
con.Close();
if (st_id != 0)
PanelA.Visible = true;
else
PanelA.Visible = false;
}
/**
protected void project_SelectedIndexChanged(Object sender, EventArgs e)
{
project.Enabled = true;
project.Items.Clear();
project.Items.Insert(0, new ListItem("SELECT PROJECT", "0"));
int unitId = int.Parse(unit.SelectedItem.Value);
if (unitId > 0)
{
string query = string.Format("Select pro_id, pro_name from tblProject where pro_id = {0} ", unitId);
BindDropDownList(project, query, "pro_name", "pro_id", "SELECT PROJECT");
project.Enabled = true;
}
}
static int i = 0;
protected void btn_addp_Click(object sender, EventArgs e)
{
int j = 0;
i++;
for (j = 0; j < i; j++)
{
TextBox tb = new TextBox();
tb.Width = 350;
tb.ID = "MP" + j.ToString();
ph.Controls.Add(tb);
}
}
*/
protected void btn_addp_Click(object sender, EventArgs e)
{
int index = pnlTB.Controls.OfType<TextBox>().ToList().Count + 1;
this.CreateTextBox("txtDynamic" + index);
}
private void CreateTextBox(string id)
{
TextBox tb = new TextBox();
tb.ID = id;
tb.Width = 350;
pnlTB.Controls.Add(tb);
Literal lt = new Literal();
lt.Text = "<div style=height:3px ></div>";
pnlTB.Controls.Add(lt);
pnlTB.Controls.Add(new LiteralControl("<div style=height:3px ></div>"));
}
protected void GetTextBoxValues(object sender, EventArgs e)
{
}
//duplicate email
protected void cv_ServerValidate(object sender, ServerValidateEventArgs e)
{
//TextBox[] participant = { participant1, participant2, participant3 };
//if (participant1.Text == participant2.Text || participant2.Text == participant3.Text || participant1.Text == participant3.Text)
//{
// cvSubmit.ErrorMessage = "* Duplicate email! Please enter different email. ";
// cvSubmit.Focus();
// e.IsValid = false;
//}
}
here is the code for submit
protected void btnSubmitSurvey_Click(object sender, EventArgs e)
{
string a_id = "";
string username = (string)Session["Username"];
string query4 = "SELECT * FROM tblAdmin WHERE a_uname='" + username + "'";
con.Open();
SqlCommand cmd4 = new SqlCommand(query4, con);
SqlDataReader dr4 = cmd4.ExecuteReader();
if (dr4.Read())
{
a_id = dr4["a_id"].ToString();
}
dr4.Close();
con.Close();
if (Page.IsValid)
{
con.Open();
string query = "CreateSurvey";
string query1 = "ListParticipant";
int surveyID;
DateTime date_now = DateTime.Now;
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#sd_id", SqlDbType.Int, 0, "sd_id");
cmd.Parameters["#sd_id"].Direction = ParameterDirection.Output;
cmd.Parameters.Add("#sd_title", SqlDbType.NVarChar).Value = txtTitle.Text;
cmd.Parameters.Add("#sd_unit", SqlDbType.NVarChar).Value = ddlunit.SelectedValue;
cmd.Parameters.Add("#sd_project", SqlDbType.NVarChar).Value = ddlproject.SelectedValue;
cmd.Parameters.Add("#sd_year", SqlDbType.NVarChar).Value = txtYear.Text;
cmd.Parameters.Add("#st_id", SqlDbType.NVarChar).Value = ddlTemplate.SelectedValue;
cmd.Parameters.Add("#sd_datecreated", SqlDbType.DateTime).Value = date_now;
cmd.Parameters.Add("#sd_createdBy", SqlDbType.NVarChar).Value = a_id;
cmd.ExecuteNonQuery();
surveyID = (int)cmd.Parameters["#sd_id"].Value;
//validate email
bool email = Regex.IsMatch(participant.Text.Trim(), "\\w+([-+.']\\w+)*#\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
if (!email)
{
lbl2.Text = "Invalid email address";
return;
}
else
{
lbl2.Text = "";
SqlCommand cmd1 = new SqlCommand(query1, con);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.Add("#sp_email", SqlDbType.NVarChar).Value = participant.Text;
cmd1.Parameters.Add("#sd_id", SqlDbType.Int).Value = surveyID;
cmd1.ExecuteNonQuery();
}
foreach (TextBox textBox in pnlTB.Controls.OfType<TextBox>())
{
if (textBox.Text != "")
{
SqlCommand cmd2 = new SqlCommand(query1, con);
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.Parameters.Add("#sp_email", SqlDbType.NVarChar).Value = textBox.Text;
cmd2.Parameters.Add("#sd_id", SqlDbType.Int).Value = surveyID;
cmd2.ExecuteNonQuery();
}
}
string message = "Your survey details has been saved.";
string url = "surveyConfirm.aspx?surveyId=" + surveyID;
string script = "window.onload = function(){ alert('";
script += message;
script += "');";
script += "window.location = '";
script += url;
script += "'; }";
ClientScript.RegisterStartupScript(this.GetType(), "Redirect", script, true);
con.Close();
}
else
{
lbl2.Text = "Fill up the information required";
}
}
}
someone please help me to solve this problem. thank you
I want it to show the selected value from the drop down list and show it on gridview. It is supposed to query from the database using Where to indicate the selected value to show. For example, I select james from the drop down list. It supposes to go to the database and query james row. After that the grid view is supposed to show only one value which james. But now I am having a problem where the grid view show every data that is available in the database.
public partial class Search_Engine : System.Web.UI.Page
{
#region Database
static string HostName = "localhost";
static string DatabaseName = "finalproject";
static string TableName = "truckinfo";
//static string TableBucket = "bucketbrigade";
static string UserName = "root";
static string Password = "";
//--- Used for access to database infomation-----
string ConnStr = "Data Source=" + HostName + ";" +
"Database=" + DatabaseName + ";" +
"User ID=" + UserName + ";" +
"Password=" + Password;
string Qry = "";
MySqlConnection Con;
MySqlCommand Cmd;
MySqlDataReader Rdr;
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
using (Con = new MySqlConnection(ConnStr))
{
Con.Open();
using (Cmd = new MySqlCommand("SELECT * FROM truckinfo", Con))
{
using (Rdr = Cmd.ExecuteReader())
{
if (Rdr.HasRows)
{
DropDownList1.DataSource = Rdr;
DropDownList1.DataValueField = "truckplateno";
DropDownList1.DataTextField = "truckplateno";
DropDownList1.DataBind();
}
}
}
}
}
}
private void BindData()
{
DataTable dt = new DataTable();
try
{
MySqlConnection Con = new MySqlConnection(ConnStr);
Con.Open();
MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM " +
DatabaseName + "." + TableName , Con);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
Con.Close();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Con = new MySqlConnection(ConnStr);
Con.Open();
try
{
String getquery;
// String a;
getquery = DropDownList1.Text;
TextBox1.Text = getquery;
// a = TextBox2.Text;
// TextBox1.Text = a;
Qry = #"SELECT * FROM finalproject.truckinfo WHERE truckplateno=" + "'" + getquery + "'" + ";";
Cmd = new MySqlCommand(Qry, Con);
Cmd.ExecuteNonQuery();
Con.Close();
BindData();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
}
You need to get the selected value using SelectedValue of dropdownlist and then query database using this value.
getquery = DropDownList1.SelectedValue;
Also you are using BindData method which will always select all data from database you need to seprate this method so only selected data is bind to gridview.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
String getquery;
getquery = DropDownList1.Text;
MySqlConnection Con = new MySqlConnection(ConnStr);
Con.Open();
MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM finalproject.truckinfo WHERE truckplateno='" + getquery + "'", Con);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
Con.Close();
}
You are calling ExecuteNonQuey function which is used to Insert or Update data in database so it will not return any data.
Also when using SqlDataAdapter you don't need to explicitly call
Open and Close function for opening and closing connection.
Change your DropDownlist_SelectedIndexChanged function to the following:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Con = new MySqlConnection(ConnStr);
DataTable dt = new DataTable();
try
{
Con.Open();
string getquery = DropDownList1.SelectedValue;
TextBox1.Text = getquery;
// a = TextBox2.Text;
// TextBox1.Text = a;
Qry = #"SELECT * FROM finalproject.truckinfo WHERE truckplateno=" + "'" + getquery + "'" + ";";
MySqlCommand ddlCMD = new MySqlCommand(Qry, Con);
MySqlDataAdapter msda = new MySqlDataAdapter(ddlCMD);
msda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
finally{
Con.Close();
}
}
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.
I wonder how to set The Picture box, and it will display 2 Images. On Value True image number 1, on value False, image number 2. I'm a noob in programming... My Record name is "oddal" dataType is "bit"
Here is my Code
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\MSI\Documents\Visual Studio 2010\Projects\Baza z własnymi batonami\Baza z własnymi batonami\Database1.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmd.Connection = cn;
pokazliste();
}
private void button1_Click(object sender, EventArgs e)
{
if (textid.Text != "" & textimie.Text != "")
{
cn.Open();
cmd.CommandText = "Insert into Table1 (id,imie) values('" + textid.Text + "','" + textimie.Text + "')";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Wpis Wprowadzony","Vindykacja by Brzoska");
cn.Close();
textid.Text = "";
textimie.Text = "";
pokazliste();
}
}
private void pokazliste()
{
listBox1.Items.Clear();
listBox2.Items.Clear();
cn.Open();
cmd.CommandText = "Select * From Table1";
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while(dr.Read())
{
listBox1.Items.Add(dr[0].ToString());
listBox2.Items.Add(dr[1].ToString());
}
}
cn.Close();
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox l = sender as ListBox;
if (l.SelectedIndex != -1)
{
listBox1.SelectedIndex = l.SelectedIndex;
listBox2.SelectedIndex = l.SelectedIndex;
textid.Text = listBox1.SelectedItem.ToString();
textimie.Text = listBox2.SelectedItem.ToString();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (textid.Text != "" & textimie.Text != "" & listBox1.SelectedIndex!=-1 )
{
cn.Open();
cmd.CommandText = "delete from Table1 where id='" + listBox1.SelectedItem.ToString() + "' and imie= '" + listBox2.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Wpis Uaktualniony", "Vindykacja by Brzoska");
pokazliste();
textid.Text = "";
textimie.Text = "";
}
}
private void button3_Click(object sender, EventArgs e)
{
if (textid.Text != "" & textimie.Text != "")
{
cn.Open();
cmd.CommandText = "Update Table1 set id='" + textid.Text + "', imie= '" + textimie.Text + "'Where id'" + textid.Text + "'and imie= '" + textimie.Text + "'";
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Wpis Usuniety", "Vindykacja by Brzoska");
pokazliste();
textid.Text = "";
textimie.Text = "";
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
}
}
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\MSI\Documents\Visual Studio 2010\Projects\Baza z własnymi batonami\Baza z własnymi batonami\Database1.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
cn.Open();
cmd.CommandText = "SELECT oddal FROM TableName WHERE (Your = Condition)";
dr = cmd.ExecuteReader();
if dr.Read()
{
if dr("oddal")
{
//Set picture box to image 1
}
else
{ //Set picture box to image 1
}
}
cn.Close();
Make sure to specify your condition in the SELECT. Also, for the future, assign meaningful names to the controls. Instead of button1, say btnInsert...