【问题标题】:Insert string array result into a gridview将字符串数组结果插入gridview
【发布时间】:2014-12-01 14:17:45
【问题描述】:

我有这个方法,它应该从我的 sql 查询结果中返回列名。 我想要的只是在 gridview 中插入并显示结果。 这是我的方法:

    protected string[] GetColumnsofServiceIDList_By_Name()
    {
        var custName = Convert.ToString(Request.QueryString["cusName"]);
        List<string> result = new List<string>();
        Exception etemp = null;
        using (SqlConnection connection = new SqlConnection("Data Source=AP;Initial Catalog=Info;User Id=sail;Password=******;App=EntityFramework"))
        {
            try
            {
                connection.Open();
                string sqlStatement = " My sql query here ";
                using (SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection))
                {
                    sqlCmd.Parameters.AddWithValue("@para1", custName);
                    sqlCmd.Parameters.AddWithValue("@para2", DropDownList1.SelectedItem.Text);
                    using (SqlDataReader reader = sqlCmd.ExecuteReader())
                    {
                        for (int i =0; i < reader.FieldCount; i++)
                        {
                            result.Add(reader.GetName(i));
                        }
                    }
                }

            }
            catch (Exception e)
            {
                etemp = e;
            }
            finally
            {
                if (connection.State == ConnectionState.Open)
                {
                    connection.Close();

                }
                if (etemp != null)
                {
                    throw etemp;
                }
            }
        }
        return result.ToArray();
    }

我希望以某种方式将上述方法插入到网格视图中,然后在我的页面上查看。

【问题讨论】:

    标签: sql asp.net gridview arrays


    【解决方案1】:

    使用DataBind 类似

    GridView1.DataSource = result;
    GridView1.DataBind();
    

    注意可以去掉

    if (connection.State == ConnectionState.Open)
                {
                    connection.Close();
    
                }
    

    因为要确保连接总是关闭,所以在 using 块内打开连接可确保在代码退出块时自动关闭连接

    【讨论】:

      猜你喜欢
      • 2013-06-10
      • 1970-01-01
      • 1970-01-01
      • 2014-01-06
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多