2015-07-19 145 views
0

我正在使用asp.net在Visual Studio中创建一个网站。 我的网站已连接到连接到SQL数据库的Web Serbice Server。将数据绑定到ASP.NET中的DropDownList

在我mainpage.aspx,在文件的顶部,我有第一以下行:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="mainpage.aspx.cs" 
Inherits=WebApplication.mainpage" %> 

在同一mainpage.aspx文件我有一个下拉列表稍后:

<asp:DropDownList ID="DropDownList1" runat="server" width="140px"></asp:DropDownList> 

在我mainpage.aspx.cs文件我写的Pade_Load()内以下代码:

DataSet Company = WebSerivce.Company(IP, DataBaseName, UserName, Password); 
DataTable cTable = Company.Table[0]; 

if(!Page.IsPostBack) 
{ 
DropDownList1.DataSource = cTable; 
DropDownList1.DataValueField = "ID_Comp"; 
DropDownList1.DataTextField = "Comp_Name"; 
DropDownList1.DataBind(); 
} 

SQL数据基表:

ID_Comp  | int   | (Primary Key) 
---------------------------- 
Comp_Name | nvarchar(50) | 

我在做什么错?我遵循多个教程的说明,但目前为止没有任何工作。有什么基本的我失踪了?

+0

您是否在cTable中获得了价值? –

+1

如何检查? – OverflowStack

+0

“使用调试”。 .1。在“数据集公司”保留一个调试点2.运行应用程序..执行将在该点进行,您可以在c表中看到该值表 – Webruster

回答

1

确保cTable中有数据。 我测试了下面的代码(注释掉服务部分)并使用本地Northwind数据库,它工作得很好。因此,再次确保服务实际上将有效数据返回到cTable。放置一个调试器断点并检查cTable的内容。

//DataSet Company = WebSerivce.Company(IP, DataBaseName, UserName, Password); 
//DataTable cTable = Company.Table[0]; 
string conn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString(); 
SqlDataSource dataSource = new SqlDataSource(conn, "select * from region"); 
DataSourceSelectArguments args = new DataSourceSelectArguments(); 
DataView view = dataSource.Select(args) as DataView; 

DataTable cTable = view.ToTable(); 

if (!Page.IsPostBack) 
{ 
    DropDownList1.DataSource = cTable; 
    DropDownList1.DataValueField = "RegionID"; 
    DropDownList1.DataTextField = "RegionDescription"; 
    DropDownList1.DataBind(); 
} 

浏览器下拉列表结果:

enter image description here

0

请尝试如下。这样你可以找到你是否绑定空数据表。基于此,我们可以进一步排除故障。

 DataTable cTable = null; 
     DataSet Company = WebSerivce.Company(IP, DataBaseName, UserName, Password); 

     if (Company != null && Company.Tables[0] != null) 
      cTable = Company.Tables[0]; 

     if (!Page.IsPostBack) 
     { 
      if(cTable != null && cTable.Rows.Count > 0) 
      { 
       DropDownList1.DataSource = cTable; 
       DropDownList1.DataValueField = "ID_Comp"; 
       DropDownList1.DataTextField = "Comp_Name"; 
       DropDownList1.DataBind(); 
      } 
      else 
      { 
       DropDownList1.DataSource = new DataTable(); 
       DropDownList1.DataBind(); 
       DropDownList1.Items.Insert(0, "Select"); 
      } 


     } 
+0

好吧,如果'cTable'是由于某种原因'null' ,你的代码会发生什么事情if(cTable.Rows.Count> 0)'?我认为一些错误会上升。所以,我认为最好用'if(Company!= null && Company.Tables [0]!= null){cTable = Company.Tables [0]; ...和其他代码。 – nelek

+0

谢谢指出。我更正了上面的代码。 –

相关问题