c# - SelectCommand 属性在调用 'Fill' 之前尚未初始化。在窗体中

标签 c#

我正在使用 C# 构建 Windows 应用程序。在我的登录表单中,我得到了在调用 fill 方法之前未初始化 Select Command 属性

代码如下:

public partial class frmlogin : Form
{
    SqlConnection con = new SqlConnection("Data Source=TH07L019;Initial Catalog=loginerror;Integrated Security=True");
    DataTable dt = new DataTable();
    SqlCommand cmd = new SqlCommand();
    SqlDataAdapter adp = new SqlDataAdapter();

    public frmlogin()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        cmd.Connection = con;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        con.Open();
        cmd.CommandText = "select * from login where username='" + txt1.Text + "' and password='" + txt2.Text +"'";
        adp.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            frmmain main = new frmmain();
            main.Show();
        }
        else
        {
            MessageBox.Show("Please enter correct name and passowrd", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}

最佳答案

在填充表格之前,您必须指定 SqlDataAdapter 的选择命令。你没有这样做。您的 SqlCommand 对象未以任何方式连接到您的 SqlDataAdapter。

 adp.SelectCommand=cmd;

关于c# - SelectCommand 属性在调用 'Fill' 之前尚未初始化。在窗体中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15803816/

相关文章:

c# - C# 中的 RSA 不会为特定 key 生成相同的加密字符串?

c# - 从俄语(西里尔文)解码 Http 响应内容

C# 杀死一个线程

c# - 打开目录文件夹中的文件

java - Unity3D 创建可编辑体素环境的最佳方式

c# - 无法动态地将 HTML 元素附加到 div

C# WPF 将 List<T> 与 Datagrid.ItemsSource 进行比较

c# - 如何使用 FindControl 获取 &lt;input of type=hidden>

c# - 初始化 VCProjectEngineObject (Microsoft.VisualStudio.VCProjectEngine.dll) 时出现错误 80040154(类未注册异常)

c# - 如何在 IdentityServer 4 中为不同角色返回不同范围?