BindDataTools.cs 3.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Web.UI.WebControls;
  6. using System.Data;
  7. namespace Bowin.Common
  8. {
  9. public static class BindDataTools
  10. {
  11. /// <summary>
  12. /// 绑定下拉框
  13. /// modify tlq 2012-4-16
  14. /// </summary>
  15. /// <param name="ddl"></param>
  16. /// <param name="T">绑定的数据源</param>
  17. /// <param name="defaultValue">显示默认第一项的内容:[----请选择----]</param>
  18. /// <param name="textField">绑定的显示名(不写默认DataTable的第二列)</param>
  19. /// <param name="valueField">绑定的值(不写默认DataTable的第一列)</param>
  20. public static void BindDataTable(this DropDownList ddl, DataTable T, string defaultValue = "", string textField = "", string valueField = "", bool IsShowSelected=true)
  21. {
  22. try
  23. {
  24. if (IsShowSelected)
  25. {
  26. if (defaultValue != "")
  27. {
  28. ddl.Items.Add(new System.Web.UI.WebControls.ListItem(defaultValue, ""));
  29. }
  30. else
  31. {
  32. ddl.Items.Add(new System.Web.UI.WebControls.ListItem("===未指定===", ""));
  33. }
  34. }
  35. for (int i = 0; i < T.Rows.Count; i++)
  36. {
  37. ddl.Items.Add(new ListItem(textField != "" ? T.Rows[i][textField].ToString() : T.Rows[i][1].ToString(), valueField != "" ? T.Rows[i][valueField].ToString() : T.Rows[i][0].ToString()));
  38. }
  39. if (ddl.Items.Count > 0)
  40. {
  41. ddl.SelectedIndex = 0;
  42. }
  43. }
  44. catch
  45. {
  46. }
  47. }
  48. /// <summary>
  49. /// 绑定下拉框
  50. /// modify tlq 2012-4-16
  51. /// </summary>
  52. /// <param name="ddl"></param>
  53. /// <param name="T">绑定的数据源</param>
  54. /// <param name="defaultValue">显示默认第一项的内容:[----请选择----]</param>
  55. /// <param name="textField">绑定的显示名(不写默认DataTable的第二列)</param>
  56. /// <param name="valueField">绑定的值(不写默认DataTable的第一列)</param>
  57. public static void BindDataTable(this ListBox ddl, DataTable T, string defaultValue = "", string textField = "", string valueField = "", bool IsShowSelected=true)
  58. {
  59. try
  60. {
  61. if (IsShowSelected)
  62. {
  63. if (defaultValue != "")
  64. {
  65. ddl.Items.Add(new System.Web.UI.WebControls.ListItem(defaultValue, ""));
  66. }
  67. else
  68. {
  69. ddl.Items.Add(new System.Web.UI.WebControls.ListItem("===未指定===", ""));
  70. }
  71. }
  72. for (int i = 0; i < T.Rows.Count; i++)
  73. {
  74. ddl.Items.Add(new ListItem(textField != "" ? T.Rows[i][textField].ToString() : T.Rows[i][1].ToString(), valueField != "" ? T.Rows[i][valueField].ToString() : T.Rows[i][0].ToString()));
  75. }
  76. if (ddl.Items.Count > 0)
  77. {
  78. ddl.SelectedIndex = 0;
  79. }
  80. }
  81. catch
  82. {
  83. }
  84. }
  85. }
  86. }