【问题标题】:How to bind variables data into GridView in windows forms如何将变量数据绑定到 Windows 窗体中的 GridView
【发布时间】:2012-05-25 06:57:09
【问题描述】:

大家好,我在 for 循环中的程序中有一些变量,变量的值将在 for 循环中动态出现。我想将这些值绑定到网格视图。我知道如何将 SQL 服务器数据绑定到网格。但是这里怎么处理。如何排列列值。谁能帮帮我。

我有这些变量

string changedFile  
int parentIssue 
List<String> Authors

我想在 for 循环中将这 3 个字段添加到网格视图中。有没有办法写出for循环的一面?

【问题讨论】:

  • 信息不足您是否定义了任何列,是否有任何特定的行集?

标签: c# winforms


【解决方案1】:

你可以试试这样的

public class BindingObject
{
    public int intMember;
    public string stringMember;
    public string nullMember;
    public BindingObject(int i, string str1, string str2)
    {
        intMember = i;
        stringMember = str1;
        nullMember = str2;
    }
} 

////Somewhere
ArrayList list = new ArrayList();
list.Add(new BindingObject(1, "One", null));
list.Add(new BindingObject(2, "Two", null));
list.Add(new BindingObject(3, "Three", null));
dataGrid1.DataSource = list;

【讨论】:

  • 这是一个更一般的例子,所以你可以添加你的列表
【解决方案2】:

只需将列表分配为数据源。

dataGridView1.DataSource = Rows;

您可以在 select 语句中排列列。

private System.Windows.Forms.DataGridViewComboBoxColumn Authors;
this.Authors.HeaderText = "Authors";
this.Authors.Name = "Authors";
this.dataGridView1.Columns.Add(this.Authors);
this.Authors.Items.AddRange(new object[] {
            "Ayn Rand",
            "Tagore"});

【讨论】:

  • 我也想将 changedFile 和 parentIssue 添加到 gird。
  • 您是如何获取数据的?存储过程?展示它,我可以提供更好的帮助。
  • 不是存储过程大哥。这些只是一个变量。
  • 我不明白为什么只对一行数据使用 DataGridView。但是,您可以创建一个类并绑定到对象数组对象 {ChangedFile='', ParentIssue = ''}。作者可以是 DataGridViewComboBoxColumn,您可以绑定到作者列表。
【解决方案3】:

如果你必须在循环本身中设置,你必须在 aspx 中为 gridview 定义一个模板

<asp:GridView ID="gridViewField" ClientIDMode="Static"   runat="Server" AutoGenerateColumns="false"
               onrowdatabound="gridViewField_RowDataBound"  HorizontalAlign="Center"  AlternatingRowStyle-BackColor="#ddecfe" >
               <Columns>                   
                   <asp:TemplateField HeaderText="Field Name">
                       <ItemTemplate>
                           <asp:Label runat="server" ID="lblFieldName"></asp:Label>
                       </ItemTemplate>
                   </asp:TemplateField>
</columns>
</asp:GridView>

在for循环中你可以得到codebehind cs文件中的每一行,如下所示

var lblFieldName= gridViewField.Rows[i].FindControl("lblFieldName") as Label
lblFieldName.Text=your loop data

i 是你的循环变量

【讨论】:

  • 问题实际上是关于 WinForms,而不是 ASP.NET WebForms。
  • 你能给我关于windows窗体的解决方案吗
  • 对不起..我错过了。我建议创建一个类,其成员为 changesdFile、ParentIssue 和作者列表。当你 for 循环创建类的 objetc 并添加到列表中时。你然后可以将datagridview绑定到这个列表并覆盖rowbound事件来操作要显示的数据
猜你喜欢
  • 2011-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多