【问题标题】:Calling a function and text box from a button从按钮调用函数和文本框
【发布时间】:2013-07-04 15:11:24
【问题描述】:

我有一个 Windows 窗体应用程序。我有一个函数,它使用 Linq to SQL 来查找我想要的记录,但我不知道如何在我的 button.click 事件中调用此函数,以便单击函数将启动我的其他函数。

另外,在我的 button.click 事件中,我需要将 textBox1.Text 值设置为 sql 语句,但如何做到这一点?

更新 - 现在修复了解决方案,这里是完整的代码:

public partial class Form1 : Form
{
    LinqtoSqlDataContext linqStud = new LinqtoSqlDataContext();

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Student student = new Student();
        string city = textBox1.Text;

        searchCity(student, city);
    }

    public Exception searchCity(Student student, string searchCity)
    {
        try
        {
            if (string.IsNullOrEmpty(searchCity))
            {
                MessageBox.Show("Please enter a value");
            }
            else
            {
                var City = from stud in linqStud.Students
                           where stud.City == searchCity
                           select stud;

                dataGridView1.DataSource = City;

            }
            return null;
        }
        catch (Exception ex)
        {
            return ex;
        }

谢谢,

尼克

【问题讨论】:

  • 欢迎使用 StackOverflow Google v2。我们很乐意为您做到这一点。
  • 你到底想让这个方法做什么?我怀疑您是否真的打算返回 Exception...您确定不希望它返回 City 变量吗?你想用这个方法的结果做什么?这个不是很清楚!
  • 对不起,如果我不是很清楚。我要做的就是调用按钮的单击事件的函数,以便它启动,以便执行 sql 并将其显示在数据网格中。

标签: c# function button linq-to-sql


【解决方案1】:

您可能不想从该方法返回异常。它可以改用void 返回类型。例如:

private void button1_Click(object sender, EventArgs e)
{
    Student student = new Student();//set up student obj...
    string city = "Foo";

    searchCity(student, city);
}

public void searchCity(Student student, string searchCity)
{
    //Do your search...
    //set the data source of your gridview

    dataGridView1.DataSource = City;
    dataGridView1.DataBind(); //Make sure you call databind
}

【讨论】:

    猜你喜欢
    • 2013-10-12
    • 1970-01-01
    • 2016-01-31
    • 2018-08-13
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多