繁体   English   中英

单击按钮时如何在文本框中显示不同的sql数据

[英]How to display different sql data in a text box when a button is clicked

MySql数据库由一个列id组成,该列id包含1到30的数字。我想在每次按下按钮时在文本框中显示1到30的数字。 但是,我的代码仅显示第一行。

我尝试了以下代码:

SqlConnection Conn = new SqlConnection("Data Source=SUMIT;Initial Catalog=Project;Integrated Security=True"); 
SqlCommand Comm1 = new SqlCommand("Select * from id", Conn); 
Conn.Open(); 
SqlDataReader DR1 = Comm1.ExecuteReader();

if (DR1.Read()) {
    textBox3.Text = DR1.GetValue(0).ToString();
}
Conn.Close();

我怀疑原因是您的按钮单击事件中包含了所有代码。 因此,每次您单击按钮时,它都会创建一个新的连接,执行查询并显示第一条记录。

我建议您重新组织代码。

例如,一次调用SetupData()函数(可能在加载时或只要执行一次就可以在任何地方调用),然后单击按钮click事件将仅包含if语句。

SqlDataReader DR1;
public void SetupData(){
     SqlConnection Conn = new SqlConnection("Data Source=SUMIT;Initial          Catalog=Project;Integrated Security=True"); 
     SqlCommand Comm1 = new SqlCommand("Select * from id", Conn); 
     Conn.Open(); 
     DR1 = Comm1.ExecuteReader();
}

 void OnButtonClick(object sender, EventArgs e)
 {
            if (DR1.Read()) {
                textBox3.Text = DR1.GetValue(0).ToString();
 }

这样做的方法很少。

首先使用SQL

将数字计数保持在按钮单击功能之外

int BtnCount = 0;

然后在按钮中单击

SqlConnection Conn = new SqlConnection("Data Source=SUMIT;Initial Catalog=Project;Integrated Security=True"); 
SqlCommand Comm1 = new SqlCommand("Select * from id WHERE ID = " + BtnCount  , Conn); 
Conn.Open(); 
SqlDataReader DR1 = Comm1.ExecuteReader();

if (DR1.Read()) {
    textBox3.Text = DR1.GetValue(0).ToString();
}
Conn.Close();
BtnCount ++;
if(BtnCount>30)
{
    BtnCount = 0;
}

其次,您可以调用集合/列表/数组中的所有数据,这也将提高系统速度

创建字符串列表

List<string> ListData = new List<string>();

像这样在构造器中填充列表

SqlConnection Conn = new SqlConnection("Data Source=SUMIT;Initial Catalog=Project;Integrated Security=True"); 
SqlCommand Comm1 = new SqlCommand("Select * from id WHERE ID = " + BtnCount  , Conn); 
Conn.Open(); 
SqlDataReader DR1 = Comm1.ExecuteReader();

while(DR1.Read()) 
{
    ListData.Add(DR1.GetValue(0).ToString());
}
Conn.Close();

然后在按钮上单击以显示BtnCount列表的BtnCount

注意 :只是给您一个想法,我还没有运行程序进行测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM