是否可以将文本框链接到数据库?

问题描述 投票:-2回答:1

我目前正在处理我的C#“ WindowForm”项目,我想知道是否可以将任何形式的文本框链接到数据库并不时更新文本框内容,以便我的应用程序的用户起来约会我愿意以这种形式(文本框)发布的信息。

谢谢,

c# database visual-studio windows-forms-designer
1个回答
0
投票

如果要从数据表中实时刷新文本,可以尝试SqlDependency

以下是一个简单的演示。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    System.Data.SqlClient.SqlConnection conn = null;
    System.Data.SqlClient.SqlCommand command = null;
    // Set connection string
    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder
    {
        DataSource = @"datasource name",
        // set database
        InitialCatalog = @"catalog name",
        // access the database using the existing windows security certificate
        IntegratedSecurity = true
    };

    private void Form1_Load(object sender, EventArgs e)
    {
        conn = new System.Data.SqlClient.SqlConnection(builder.ConnectionString);
        command = conn.CreateCommand();
        command.CommandText = "select text from dbo.TableText where id<>20 order by id desc ";

        // Start
        SqlDependency.Start(builder.ConnectionString);
        // Get data
        GetData();
    }

    private void GetData()
    {
        command.Notification = null;
        SqlDependency dependency = new SqlDependency(command);
        dependency.OnChange += new OnChangeEventHandler(sqlDependency_OnChange);

        using (SqlDataAdapter adapter = new SqlDataAdapter(command))
        {
            System.Data.DataSet ds = new DataSet();
            adapter.Fill(ds, "test");
            string text = ds.Tables["test"].Rows[0]["Text"].ToString();
            textBox.Text = text;
        }
    }

    void sqlDependency_OnChange(object sender, SqlNotificationEventArgs e)
    {
        // Because it is a child thread, you need to update the ui with the invoke method.
        if (this.InvokeRequired)
        {
            this.Invoke(new OnChangeEventHandler(sqlDependency_OnChange), new object[] { sender, e });
        }
        else
        {
            SqlDependency dependency = (SqlDependency)sender;
            dependency.OnChange -= sqlDependency_OnChange;
            // After the notification, the current dependency is invalid, you need to re-get the data and set the notification.
            GetData();
        }
    }

    private void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
        // Clear resource
        SqlDependency.Stop(builder.ConnectionString);
        conn.Close();
        conn.Dispose();
    }
}

有关SqlDependency的更多信息,可以参考Detecting Changes with SqlDependency

希望这可以帮助您。

© www.soinside.com 2019 - 2024. All rights reserved.