【问题标题】:Why won't my labels stay changed为什么我的标签不会保持不变
【发布时间】:2015-01-01 21:05:28
【问题描述】:

当我运行我的代码时,标签保持不变,但当我调试它时,我可以看到文本发生变化,然后在运行完成后又变回来

public void getData(string a) 
{
    SqlConnection conn = new SqlConnection(@"Data Source=MASSI\FABERSERVER;Initial Catalog=Data.mdf;Integrated Security=True");
    conn.Open();
    SqlCommand command = new SqlCommand("Select UserID,UserName,Email FROM Login Where UserName= '" + a + "'", conn);
    SqlDataReader reader = command.ExecuteReader();

    while (reader.Read())
    {
        label1.Text = reader["UserID"].ToString();
        label2.Text = reader["UserName"].ToString();
        label3.Text = reader["Email"].ToString();
    }

    conn.Close();
}

【问题讨论】:

  • 网络表单?赢表格? WPF?
  • 您可能只在 1 行之后。您的 While 循环应该在找到该单行后退出,并且您应该使用 if (reader.HasRows) 添加逻辑,用于何时找不到该行。此链接讨论了一种更好的方法:stackoverflow.com/questions/7836517/… 但我想它有点高级。
  • 您的应用程序对 SQL 注入开放。请改用参数化查询。
  • 您是在重新加载表单然后不再调用 getData() 吗?更改不会自动保留。

标签: c#


【解决方案1】:

以防万一,试试这个:

public void getData(string a) {
        SqlConnection conn = new SqlConnection(@"Data Source=MASSI\FABERSERVER;Initial Catalog=Data.mdf;Integrated Security=True");
        conn.Open();
        SqlCommand command = new SqlCommand("Select UserID,UserName,Email FROM Login Where UserName= '" + a + "'", conn);
        SqlDataReader reader = command.ExecuteReader();

        string id, name, email;

        while (reader.Read())
        {
            id = reader["UserID"].ToString();
            name = reader["UserName"].ToString();
            email = reader["Email"].ToString();

        }
        conn.Close();

        label1.Text = id;
        label2.Text = name;
        label3.Text = email;
    }
}

希望,它会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-23
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多