我的方法没有被我的应用程序调用。我使用过断点,它从未在代码中启动过。我正在使用Azure数据库构建一个C#Windows窗体应用程序,但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 System.Data.SqlClient;
using System.Configuration;
namespace MyWinFormsProj
{
public partial class CompanyForm : Form
{
public CompanyForm()
{
InitializeComponent();
}
//Connection String
string cs = ConfigurationManager.ConnectionStrings
["MyConnetion"].ConnectionString;
// Load all employees
private void dataEmployees_Load()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select fname,ename FROM dbo.Users", con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}
// Crate company
private void createCompany_Click_1(object sender, EventArgs e)
{
if (textBoxCompanyName.Text == "")
{
MessageBox.Show("Fill out information");
return;
}
using (SqlConnection con = new SqlConnection(cs))
{
//Create SqlConnection
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into dbo.Company (companyName)
values(@companyName)", con);
cmd.Parameters.AddWithValue(
"@companyName", textBoxCompanyName.Text);
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
MessageBox.Show("Grattis! Du har skapat ett företag");
}
}
}
}
第二种方法正在运行并正在做它应该做的事情,但第一种方法从未被调用过..
答案 0 :(得分:1)
您需要在gridView onLoad上设置事件处理程序并将此方法传递给处理程序
public void GridView_OnLoad(object sender, EventArgs e)
{
dataEmployees_Load();
}
答案 1 :(得分:1)
您需要修改方法签名,如下所示:
private void dataEmployees_Load(object sender, EventArgs e)
然后,在你的GirdView中,你需要将此函数设置为事件“onload”的处理程序:
OnLoad="dataEmployees_Load"
答案 2 :(得分:0)
谢谢你们的答案,这有助于我解决问题。就像你说的那样,问题在于没有被调用的方法。所以我直接在initiliazeComponent上调用它。
public partial class CompanyForm : Form
{
public CompanyForm()
{
InitializeComponent();
Load += new EventHandler(dataEmployees_Load); //Added this code
}
// Load all employees
private void dataEmployees_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select fname,ename FROM dbo.Users", con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}