在标签上显示MySql中的值

时间:2016-09-23 13:28:03

标签: c# mysql datagridview

如何在标签上显示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的标签上显示?

2 个答案:

答案 0 :(得分:0)

根据您的需要,

IOException

所以

对于数据表中的第一行和第一列(使用序号位置),它将是这样的

lbl_cliente_codigo.Text = dt.Rows[row number]["column name" | column ordinal];

如果你在每个

中循环
lbl_cliente_codigo.Text = dt.Rows[0][0];

答案 1 :(得分:0)

由于我不知道您的完整代码是什么样的,我将编写所有需要的元素(我的方法,但很多可能):

//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!");
}

可能有错误(希望不是)。