我的 MySql
数据库由一列 id
组成,其中包含从 1 到 30 的数字。我想在每次按下按钮时在文本框中显示数字 1 到 30被按下。但是,我的代码仅显示第一行,即 1。
我试过以下代码:
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();
最佳答案
有几种方法可以做到这一点。
首先使用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
注意:这只是为了让你知道我没有运行程序来测试。
关于c# - 单击按钮时如何在文本框中显示不同的sql数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34261739/