[英]Populate DataGrid from Mysql Database
首先,我是C#和Visual Studio的新手。 我遵循了有關如何從MySql表填充DataGridView的教程。 我多次檢查復制錯誤,但沒有發現任何錯誤。 代碼是這樣的:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace DataGridMain
{
public partial class Form1 : Form
{
private string server;
private string database;
private string uid;
private string password;
private MySqlConnection connection;
private MySqlDataAdapter mySqlDataAdapter;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
server = "localhost";
database = "elphoapp";
uid = "username";
password = "password";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
if (this.OpenConnection() == true)
{
mySqlDataAdapter = new MySqlDataAdapter("select * from users", connection);
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
dataGridView1.DataSource = DS.Tables[0];
this.CloseConnection();
}
}
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
default:
MessageBox.Show(ex.Message);
break;
}
return false;
}
}
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
}
}
我似乎找不到問題,也沒有錯誤顯示。
當您不熟悉Visual Studio時,我的建議是您必須學習的第一件事是調試。 它將為您節省很多時間。 在這種情況下,在form_load中放置一個斷點並逐步運行代碼。 您可以通過這種方式查看正在發生的情況,並檢查所有變量。 我說這是因為我看不到您的代碼中的任何錯誤,所以可能您甚至沒有連接到數據庫。 調試代碼,您可能會明白為什么
好吧,我想通了! 我要做的就是從Form1()函數內部調用Form1_Load。 目前一切似乎都正常。 謝謝,C#充滿了該死的驚喜。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.