在标签上显示MySql的值
本文关键字:MySql 的值 显示 标签 | 更新日期: 2023-09-27 18:08:25
如何在标签上显示MySql的值?
MySqlConnection conn = null;
string strConn = @"Server=localhost;Database=locadora;Uid=root;Pwd='';Connect Timeout=30;";
conn = new MySqlConnection(strConn);
conn.Open();
string mSQL = "SELECT cliente_codigo FROM cliente WHERE cliente_nome LIKE '%" + txt_nomepesquisa.Text"%'";
MySqlCommand cmd = new MySqlCommand(mSQL, conn);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
this.dgv_cliente.DataSource = dt;
这个显示在数据网格视图中。如何在一个名为lbl_cliente_codigo
的标签上显示?
根据你的需要,
lbl_cliente_codigo.Text = dt.Rows[row number]["column name" | column ordinal];
对于数据表中的第一行和第一列(使用顺序位置),它将像这样
lbl_cliente_codigo.Text = dt.Rows[0][0];
的值如果你在a中循环每个
foreach (DataRow row in dt.Rows)
{
lbl_cliente_codigo.Text = row[0].ToString()
// or
lbl_cliente_codigo.Text = row["Column Name"].ToString()
}
因为我不知道你的完整代码看起来像什么,我将编写所有需要的元素(我的方法,但许多可能):
//put this on top under "public partial class"
private string conn;
MySqlConnection connect;
//make a private void which connects to database
private void db_connection()
{
try
{
conn = "Server=127.0.0.1;Database=locadora;Uid=root;Pwd=;";
connect = new MySqlConnection(conn);
connect.Open();
}
catch (MySqlException e)
{
throw;
}
finally
{
MessageBox.Show("No connection!");
}
//Make private bool with MySql code
private bool Read_Value()
{
db_connection();
MySqlCommand cmdRead = new MySqlCommand(string _client);
//I just used your code. If not right, edit
cmdRead.CommandText = "SELECT cliente_codigo FROM cliente WHERE cliente_codigo =@_cliente_codigo AND cliente_nome LIKE '%" + txt_nomepesquisa.Text"%'";
cmdRead.Parameters.AddWithValue("@_cliente_codigo" _client);
cmdRead.Connection = connect;
MySqlDataReader dbRead= cmdRead.ExecuteReader();
if (dbRead.Read())
{
lbl_cliente_codigo.Text = dbRead.GetString(0);
connect.Close();
return true;
}
else
{
connect.Close();
return false;
}
}
//use it in, lets say button click
//(put in button event)
string _client = lbl_cliente_codigo.text;
try
{
bool c = Read_Value(_client);
if(c)
{
lbl_cliente_codigo.text = _client;
}
}
catch
{
MessageBox.Show("No connection!");
}