在asp.net中以编程方式创建Listview

本文关键字:方式 创建 Listview 编程 asp net | 更新日期: 2023-09-27 18:00:57

我是ASP.net的新手,我想通过编程创建一个动态Listview组件。我为Gridview和Datatable找到了如何做到这一点的示例,但没有为Listview找到。有可能吗?有人知道一个好的教程吗?

在asp.net中以编程方式创建Listview

试试这个

private void CreateMyListView()
 {
  // Create a new ListView control.
  ListView listView1 = new ListView();
  listView1.Bounds = new Rectangle(new Point(10,10), new Size(300,200));
  // Set the view to show details.
  listView1.View = View.Details;
  // Allow the user to edit item text.
  listView1.LabelEdit = true;
  // Allow the user to rearrange columns.
  listView1.AllowColumnReorder = true;
  // Display check boxes.
  listView1.CheckBoxes = true;
  // Select the item and subitems when selection is made.
  listView1.FullRowSelect = true;
  // Display grid lines.
  listView1.GridLines = true;
  // Sort the items in the list in ascending order.
  listView1.Sorting = SortOrder.Ascending;
  //Creat columns:
  ColumnHeader column1 = new ColumnHeader();
  column1.Text = "Customer ID";
  column1.Width = 159;
  column1.TextAlign = HorizontalAlignment.Left;
  ColumnHeader column2 = new ColumnHeader();
  column2.Text = "Customer name";
  column2.Width = 202;
  column2.TextAlign = HorizontalAlignment.Left;
  //Add columns to the ListView:
  listView1.Columns.Add(column1);
  listView1.Columns.Add(column2); 

  // Add the ListView to the control collection.
  this.Controls.Add(listView1);
 }

或者看看的例子

 Imports System
 Imports System.Drawing
 Imports System.Windows.Forms
Public Class listview
Inherits Form
Friend WithEvents btnCreate As Button
Public Sub New()
    Me.InitializeComponent()
End Sub
Private Sub InitializeComponent()
    btnCreate = New Button
    btnCreate.Text = "Create"
    btnCreate.Location = New Point(10, 10)
    Me.Controls.Add(btnCreate)
    Text = "Countries Statistics"
    Size = New Size(450, 245)
    StartPosition = FormStartPosition.CenterScreen
End Sub
Private Sub btnCreate_Click(ByVal sender As System.Object, _
                        ByVal e As System.EventArgs) Handles btnCreate.Click
    Dim lvwCountries As ListView = New ListView
    lvwCountries.Location = New Point(10, 40)
    lvwCountries.Width = 420
    lvwCountries.Height = 160
    Controls.Add(lvwCountries)
End Sub
Public Shared Sub Main()
    Application.Run(New Exercise)
End Sub
End Class

如何处理此任务的基本思想。关键概念与GridView所需要的概念相同

1( 您需要在页面上的某个位置放置ListView-一个容器

2( 此容器需要在服务器上运行,因此您的C#代码(服务器评估(可以向其中添加ListView。您可以使用两个示例容器:Panel和具有runat=server属性的标准div标记。

3( 选择何时创建ListView的代码将被调用以及如何。我建议您将其定义为方法,并从您想要的事件中调用它,例如:

protected void Page_Load(object sender, EventArgs e)
{
    // Call your method here so the ListView is created
    CreateListView();
}
private void CreateListView()
{
    // Code to create ListView here
}

4( 在上面的方法中使用下面的代码来创建ListView并将其添加到容器中,如下所示:

var myListView = new ListView();
containerName.Controls.Add(myListView);

您需要添加到ListView属性中,使其在明显的数据绑定之上具有美观性。

在此页面上找到的代码包含一些您最可能想要使用的示例属性。