简体   繁体   中英

Programatically select and bind Sharepoint list items

I have some code to bind SharePoint list items to text boxes. But I only got the code to bind one item. My list contains two columns (ID and Name):

*ID Name*

1 Steven

2 Joe

3 Henry

This code picks out the Name field from the first item (that means my textbox will show "Steven":

try
{
    SPQuery query = new SPQuery();
    query.Query = "";
    query.ViewFields = "";
    query.RowLimit = 100;

    using (SPSite site = new SPSite(SPContext.Current.Web.Url))
    {
        using (SPWeb web = site.OpenWeb())
        {
            SPList list = web.Lists.TryGetList("Employee List");

            if (list != null)
            {
                 if (list.GetItems(query).GetDataTable() != null)
                 {
                     DataTableReader rdr = list.GetItems(query).GetDataTable().CreateDataReader();

                     if (rdr.Read())
                     {
                         TextBox1.Text = rdr["Name"].ToString();

                         rdr.Close();
                     }
                 }
            }
        }
    }
}

How to select the rest of them names? I was thinking about an if-statement to check if field = ID (1, 2, 3) etc. but couldn't find out anything.

Use a while loop and it should loop through all the "Name" values.

if (list.GetItems(query).GetDataTable() != null)
{
    using (DataTableReader rdr = list.GetItems(query).GetDataTable().CreateDataReader())
    {
        while (rdr.Read())
        {
            TextBox1.Text = rdr["Name"].ToString();
        }
    }
}

Addtionally you should be using a using statement to ensure that Dispose() and Close() are both called on the DataTableReader.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM