从按钮调用函数和文本框

时间:2013-07-04 15:11:24

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

我有一个Windows窗体应用程序。我有一个函数使用Linq to SQL来查找我想要的记录,但我不知道如何在我的button.click事件中调用此函数,以便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;
        }

谢谢,

尼克

1 个答案:

答案 0 :(得分:0)

您可能不希望从该方法返回异常。它可以使用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
}