2016-03-21 115 views
0

首先,我是C#和Visual Studio的新手。 我跟随了关于如何从MySql表填充DataGridView的教程。 我检查了多次复制错误,但我没有找到任何。 的代码是这样的:我好像从Mysql数据库填充DataGrid

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; 
    } 
} 
    } 
    } 

无法找到问题并没有错误显示。

回答

0

由于您是Visual Studio的新手,我的建议是您必须学习的第一件事就是调试。它会为你节省很多时间。在这种情况下,在你的form_load中放置一个断点并逐步运行代码。你可以这样看看发生了什么,并检查所有的变量。我这样说是因为我看不到你的代码中有任何错误,所以可能你甚至连接到数据库。调试你的代码,你可能会看到为什么

+0

哦,猜猜看是什么。 Debug.WriteLine也不起作用。 无论我把它放在哪里都行不通。再次没有错误,没有什么是调试。 我想C编程语言是其中的一种...... –

0

好吧,我明白了! 我只需要从Form1()函数中调用Form1_Load。 现在一切似乎都正常。 谢谢,C#充满了该死的惊喜....

+0

嗯......是你的“控制台应用程序”类型的项目?如果是这样,显然Form_Load不会被调用,因为它是一个Windows窗体事件处理程序。 – Pikoh