我的数据库中有一个表,名为“ students”,其中有人数,姓名,地址……。
我有一个表格,一次可以为一个学生加载所有信息,还有一个“下一步”按钮和“返回”按钮。
我怎样才能迭代到mysql的下一行(或上一行)(以便能够看到下一个学生的信息)?
我尝试使用主键(自动递增)进行迭代,当我想查看下一条记录时,我向ID加1或减去1以查看前一条记录。
但是,如果删除一条记录,它将显示一个空记录。你能指出我正确的方向吗?
我正在使用WinForms
对不起我的英语。
string config = "server=localhost; userid = root; database = databaseName";
MySqlConnection con = new MySqlConnection(config);
MySqlDataReader reader = null;
string query = "SELECT * FROM students WHERE id = " + id; //id is the primary Key (auto increment)
MySqlCommand command = new MySqlCommand(query, con);
con.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
string studentName = (string)reader["studentName"];
string studentNum = (string)reader["studentNum"];
tbstudentName.Text = Convert.ToString(studentName);
tbstudentNum.Text = Convert.ToString(studentNum);
.....
}
con.Close();
您不应该在每次要查看下一条记录时都调用数据库。尝试将所有数据读入列表。
我不确定您使用的是什么。WinForms?WPF?
如果使用WinForms,则需要执行以下操作。
public class Student
{//First create a class to hold your data in
public string Name { get; set; }
public string Num { get; set; }
}
public class MyForm : Form
{
int Index = 0;
List<Student> FormData { get; set; }
void GetData()
{
//This will hold all your data in memory so you do not have to make a database call each and every "iteration"
List<Student> dbData = new List<Student>();
string config = "server=localhost; userid = root; database = databaseName";
MySqlConnection con = new MySqlConnection(config);
MySqlDataReader reader = null;
string query = "SELECT * FROM students";
MySqlCommand command = new MySqlCommand(query, con);
con.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
Student newStudent = new Student();
newStudent.Name = (string)reader["studentName"];
newStudent.Num = (string)reader["studentNum"];
//Add data to the list you created
dbData.Add(newStudent);
.....
}
con.Close();
//set the Form's list equal to the one you just populated
this.FormData = dbData;
}
private void BindData()
{
//If winforms
tbstudentName.Text = FormData[Index].Name;
tbstudentNum.Text = FormData[Index].Num;
//If wpf you will have to use view models and bind your data in your XAML but I am assuming you are using
//winforms here.
}
private void NextRecord()
{ //If you reached the end of the records then this will prevent IndexOutOfRange Exception
if (Index < FormData.Count - 1)
{
Index++;
BindData();
}
}
private void PreviousRecord()
{
if (Index != 0)
{
Index--;
BindData();
}
}
}
现在,以上场景将使其快速工作;但是,有更好的方法可以在需要更改数据时为您提供帮助。我建议使用WinForms绑定。您可以在这里查看它http://msdn.microsoft.com/en-us/library/c8aebh9k(v=vs.110).aspx
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句