Populating a SelectList from a DataTable

前端 未结 8 1063
说谎
说谎 2020-12-18 11:12

I ran a query and returned a datatable,

myDataAdapter.Fill(myDataTable);

Now what is the best way to load the row values \"Value\" and \"Te

相关标签:
8条回答
  • 2020-12-18 11:18

    Assuming your DataTable has 2 columns (text and value), you have to

    1. Set the DropDownList's DataSource to the table
    2. Set the DataTextField to the text column name
    3. Set the DataValueField to the value column name
    4. Call the Databind method
    
    0 讨论(0)
  • 2020-12-18 11:24

    It's way too late for me to answer but I think this might be an optimized way to do it, hope it works.

    List<SelectListItem> listName= new List<SelectListItem>();
    
    for (int i = 0; i < datatableName.Rows.Count; i++)
       {
         listName.Add(new SelectListItem { Text = datatableName.Rows[i]["ColumnName"].ToString(), Value = datatableName.Rows[i]["ColumnName"].ToString() });
       }
    

    You can also loop through the column names as well by applying another loop and using that as an index at the column identifier of the datatable.

    Thank You.

    0 讨论(0)
  • 2020-12-18 11:27

    Completely in the line of 'Dot Net Developer' answer, I add my full implementation of his/her solution:

     /// <summary>
        /// retrieve the document types from the database
        /// </summary>
        /// <returns></returns>
        private SelectList FillDocumentTypes()
        {
            SqlCommand command = null;
            SqlConnection _sqlcon = null;
            SelectList result = null;
            try
            {
                _sqlcon = new SqlConnection(connectionString);
                string commandText = string.Concat("select Code, [Description] from tblC2scDocumentTypeCodes");
    
                command = new SqlCommand(commandText, _sqlcon);
                _sqlcon.Open();
                SqlDataAdapter dataAdapter = new SqlDataAdapter(commandText, _sqlcon);
    
                DataTable dataTable = new DataTable();
    
                dataTable.Locale = System.Globalization.CultureInfo.InvariantCulture;
                dataAdapter.Fill(dataTable);
    
                //populate selectlist with DataTable dt
                result = new SelectList(dataTable.AsDataView(), "Code", "Description");
    
                _sqlcon.Close();
                return result;
    
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
              }
            finally
            {
                command.Dispose();
                _sqlcon.Dispose();
            }
    
        }
    
    0 讨论(0)
  • 2020-12-18 11:28

    Datatable contains an extension method AsDataView . You can use this extension method to populate SelectList from a DataTable. A sample of code :

    DataTable dt = new DataTable();
    dt.Columns.Add("Id", typeof(string));
    dt.Columns.Add("Name", typeof(string));
    dt.Rows.Add("1", "test");
    //populate selectlist with DataTable dt
    var selectList = new SelectList(dt.AsDataView(), "Id", "Name");
    

    Here Id in the SelectList is the selectedValue column and Name is the DisplayMember column.

    0 讨论(0)
  • 2020-12-18 11:31

    I couldn't find a way to directly bind the DataTable to a SelectList so I resolved creating an Extension method to accomplish this:

    public static SelectList ToSelectList(this DataTable table, string valueField, string textField)
    {
        List<SelectListItem> list = new List<SelectListItem>();
    
        foreach (DataRow row in table.Rows)
        {
            list.Add(new SelectListItem() 
            {
                Text = row[textField].ToString(), 
                Value = row[valueField].ToString()
            });
        }
    
        return new SelectList(list, "Value", "Text");
    }
    
    0 讨论(0)
  • 2020-12-18 11:33

    Here is what I came up with it seems to work well, But I was wondering if this is the best way.

    First I created an object that looks like my results form my query,

    public class MyTestObj
    {
        public string Value_CD { get; set; }
        public string Text_NA { get; set; }
    }
    

    Then I create a ILIST and populate it with the datatable rows

    IList<MyTestObj> MyList = new List<MyTestObj>();
    foreach (DataRow mydataRow in myDataTable.Rows)
    {
      MyList.Add(new MyTestObj()
      {
        Value_CD = mydataRow["Value"].ToString().Trim(),
        Text_NA  = mydataRow["Text"].ToString().Trim()                      
      });
    }
    
    return new SelectList(MyList, "Value_CD", "Text_NA");
    

    Any comments on this approach?

    0 讨论(0)
提交回复
热议问题