【问题标题】:How to bind userControls inside a DataRepeater in Windows Forms c#?如何在 Windows 窗体 c# 中的 DataRepeater 中绑定 userControls?
【发布时间】:2023-04-01 09:03:02
【问题描述】:

如何在 Windows Forms c# 中的 DataRepeater 中绑定 userControls?

我不想使用这种方法:http://blogs.msdn.com/b/vsdata/archive/2009/08/12/datarepeater-control-for-windows-forms.aspx,但我想以编程方式从 DataSet/DataTable 进行绑定。 在中继器内部仅用于测试,我放置了一个文本框和一个标签。还有一个 UserControl,它也包含两个控件:一个标签和一个文本框。 到目前为止,只更新了第一个标签和文本框,但没有更新用户控件。我想念什么?

这是加载事件

private void DataRepeaterForm_Load(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection("Data Source=ADRIAN-PC; Initial Catalog=AdventureWorks2008R2; Integrated Security=true;User id=;password=");

            SqlCommand cmd = new SqlCommand("Select * from Person.Person", con);
            SqlDataAdapter adapt = new SqlDataAdapter(cmd);

            DataTable items = new DataTable();
            adapt.Fill(items);

            textBox1.DataBindings.Add("Text", items, "FirstName");
            label1.DataBindings.Add("Text", items, "LastName");

            TextBox myUcTextBox1 = (TextBox)myUC1.Controls.Find("textBox1", true).First();

            if( myUcTextBox1 != null)
                myUcTextBox1.DataBindings.Add("Text", items, "LastName");

            dataRepeater1.DataSource = items;
        }

我是否也应该使用其他事件,例如 DrawItem,...? 问候。

【问题讨论】:

    标签: c# winforms dataset datarepeater


    【解决方案1】:

    使用BindingSource添加绑定:

    BindingSource bindingSource1 = new BindingSource();
    bindingSource1.DataSource = items;
    textBox1.DataBindings.Add("Text", bindingSource1, "FirstName");
    label1.DataBindings.Add("Text", bindingSource1, "LastName");
    dataRepeater1.DataSource = bindingSource1;
    

    【讨论】:

    • 这并不能解决我的问题,dataRepeater 内的 usercontrol 控件未绑定。
    • @AlexaAdrian 验证您的 DataTable 中是否有任何数据
    • 我愿意。也就是说,我找到了一个解决方案:我在 userControl 中创建了属性,因此我使用 get 和 set 访问了文本框和标签作为属性。现在正在工作
    • MyUC myUC1 = ((MyUC)e.DataRepeaterItem.Controls.Find("myUC1", true)[0]); myUC1.TxtBox1 = PersonsDT.Rows[e.DataRepeaterItem.ItemIndex]["FirstName"].ToString(); myUC1.LblCtrl1 = PersonsDT.Rows[e.DataRepeaterItem.ItemIndex]["LastName"].ToString();
    • @AlexaAdrian 已验证 - 使用用户控件只需创建公共属性并将它们绑定到 bindingsource。与组合框相同 - 使用它的 SelectedItem 属性进行绑定。您还需要用可能的值填充组合框(这不是绑定部分)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-08
    相关资源
    最近更新 更多