【问题标题】:Passing multiple Query Parameters to TableAdaper Fill Method C#将多个查询参数传递给 TableAdaper 填充方法 C#
【发布时间】:2020-04-15 20:31:40
【问题描述】:

我正在尝试在 Visual Studio 中创建一个程序,该程序使用具有多个参数的查询来使用 C# 中的 TableAdapter 方法填充数据网格视图。该数据库是由服务器管理工​​作室管理的 SQL Server Express 数据库。我使用 DataSet Designer 进行了 TableAdapter 查询,并且在从那里进行测试时它可以工作。这是查询:

SELECT Customer, Department, Brand, Model, TotalTime, AMPM, InvoiceNumber, Day, TechName, EntryID, Remarks, Date FROM Entries WHERE (TechName = @TechName) AND Date BETWEEN @Date1 AND @Date2

该程序应该让用户从组合框中选择数据库中的名称并从 datetimepicker 框中输入两个日期,然后他们单击一个按钮并运行查询并使用结果更新 datagridview。下面是按钮的代码。

    private void searchButton_Click(object sender, EventArgs e)
    {

        if ((techNameComboBox.Text.Length > 0)
        && (dateDateTimePicker.Text.Length > 0)
        && (dateDateTimePicker1.Text.Length > 0))
        {
            try
            {
                this.entriesTableAdapter.FillByDateRange(
                    this.timeSheetEntriesDataSet.Entries, (techNameComboBox.Text, dateDateTimePicker.Text, dateDateTimePicker1.Text));
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

    }

我得到一个“没有给出与所需的形式参数'Date1'错误相对应的参数...使用表适配器时会自动为您生成很多代码,我不知道是否有什么在为了将多个参数传递给该方法而没有生成的背景,或者如果我的按钮单击代码丢失了一些东西,但它不会将多个参数传递给查询,只有第一个参数。如果我设计一个查询只使用一个参数并使用上面相同的代码(减去额外的两个参数)就可以了。

为了让它发挥作用,我缺少什么?我对C#只有模糊的理解,所以我一辈子都搞不清楚。

【问题讨论】:

    标签: c# visual-studio datagridview parameters tableadapter


    【解决方案1】:

    根据您的错误,您应该使用 dateTimePicker.Value 而不是

    dateTimePicker.Text.

    因为 dateTimePicker.Text 只是一个字符串类型,而

    dateTimePicker.Value 是一种日期时间。

    我们需要让它们对应起来。

    这是我测试过的代码。

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    
        private void entriesBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.entriesBindingSource.EndEdit();
            this.tableAdapterManager.UpdateAll(this.testDBDataSet);
    
        }
    
        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'testDBDataSet.Entries' table. You can move, or remove it, as needed.
            this.entriesTableAdapter.Fill(this.testDBDataSet.Entries);
    
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            TestDBDataSet dBDataSet = new TestDBDataSet();
            entriesTableAdapter.FillBy(dBDataSet.Entries, textBox1.Text, dateTimePicker1.Value, dateTimePicker2.Value);
            entriesDataGridView.DataSource = dBDataSet.Entries;
    
        }
    }
    

    结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多