2017-08-07 96 views
0
 DataTable Titles = new DataTable(); 

     SqlConnection connection = new SqlConnection(AssessmentData.GetConnection()); 
     connection.Open(); 
     SqlCommand sqlGetTitles = new SqlCommand("[HRO_AAT].[dbo].[GetPositionLibrary]", connection); 
     sqlGetTitles.CommandType = System.Data.CommandType.StoredProcedure; 
     SqlDataAdapter sqlTitles = new SqlDataAdapter(sqlGetTitles); 
     sqlTitles.Fill(Titles); 

     connection.Close(); 

     gvPositions.DataSource = Titles.DefaultView; 

我用上面的代码来填充基于从下拉列表中,并在SQL Server数据库的存储过程,用户的选择在ASP.NET数据网格填充一个datgrid。它似乎运行正常,因为我在函数中放置了一个断点,并且它没有错误地遍历每一行,但它没有显示数据网格,并且存储过程正在返回数据。任何帮助,将不胜感激。谢谢。从存储过程

+0

显示整个功能。看起来你的DataTable对象是本地的,并且在函数完成之后它被GC收集器销毁。 – Ramunas

+0

这里有很多样品。 http://www.c-sharpcorner.com/uploadfile/anjudidi/example-of-datagrid-in-Asp-Net/ – Jeremy

+0

尝试将数据源绑定到标题,而不是标题.DefaultView –

回答

0

你有没有考虑在返回DataTable的方法中包装你的代码?

例如:

public DataTable Get_Stored_Procedure_Data() 
    { 
     DataTable Titles = new DataTable(); 

     SqlConnection connection = new SqlConnection(AssessmentData.GetConnection()); 
     try 
     { 
      connection.Open(); 
      SqlCommand sqlGetTitles = new SqlCommand("[HRO_AAT].[dbo].[GetPositionLibrary]", connection); 
      sqlGetTitles.CommandType = System.Data.CommandType.StoredProcedure; 
      SqlDataAdapter sqlTitles = new SqlDataAdapter(sqlGetTitles); 
      sqlTitles.Fill(Titles); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
     finally 
     { 
      connection.Close(); 
     } 

     return Titles; 
    } 

然后:

 DataTable results = Get_Stored_Procedure_Data(); 
    gvPositions.DataSource = Titles.DefaultView; 

另外,我补充一个尝试,捕捉,最后是良好实践。

+0

我想要做的是让用户从下拉列表中选择标题形式,然后根据该选择填充gridview。该函数位于下拉式OnSelectedIndexChanged事件中。 –

+0

在您的表单中创建公用数据表项public_dt,并立即将其绑定到您的DGV。在事件OnSelectedIndexChanged中,调用我上面创建的方法,并将其设置为等于public datatable public_dt。 –

+0

你能解决你的问题吗? –