这适用于在列表框中显示数据库中的项目,但我需要如果我在列表框中选择一个值,它将有关该人的信息显示回文本框。那是我无法上班的事情。
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);
}
}
}
}