C#将DataRow []变量从后面的代码传递给.netpage

时间:2016-01-09 13:09:02

标签: c# asp.net

我正在尝试将protected DataRow[] msgArray;从代码隐藏传递到.net页面。

msgArray包含我选择的数据库表中的行,当我Response.Write(msgArray[0]["comment"])时,它正确输出我存储在数据库注释列中的内容。 问题是,当我加载我执行此操作的页面时,我无法在我的.net页面中执行相同的操作:

<asp:Panel ID="commentSection" runat="server">
        <%= msgArray[0]["comment"] %>
    </asp:Panel>

我得到Object reference not set to an instance of an object.

我做错了什么?

这是我的代码隐藏(.cs):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using MySql.Data.MySqlClient;

namespace Groups
{
    public partial class Group : System.Web.UI.Page
    {
        MySql.Data.MySqlClient.MySqlConnection conn;
        MySql.Data.MySqlClient.MySqlCommand cmd;
        MySql.Data.MySqlClient.MySqlDataReader reader;
        String queryStr;
        String gname;
        String gtype;
        String uname;
        DataTable group = new DataTable();
        DataTable msg = new DataTable();

        protected DataRow[] msgArray; 



        protected void Page_Load(object sender, EventArgs e)
        {
            String id = Request.QueryString["id"];

            if (id != null)
            {
                String connString = System.Configuration.ConfigurationManager.ConnectionStrings["GroupsConnString"].ToString();
                conn = new MySql.Data.MySqlClient.MySqlConnection(connString);

                conn.Open();
                queryStr = "SELECT g.*, (SELECT COUNT(id) FROM app_groups.users_groups_leg ugl WHERE ugl.id_group = g.id) as member_count FROM app_groups.groups g WHERE g.id = " + id;
                cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);

                group.Load(reader = cmd.ExecuteReader());
                var groupArray = group.AsEnumerable().ToArray();
                reader.Close();

                int member_count = 0;
                int.TryParse(groupArray[0]["member_count"].ToString(), out member_count);

                Panel grInfo = new Panel();
                grInfo.Controls.Add(new LiteralControl("<br/><div class='panel panel-primary'><div class='panel-heading'><h2>" + groupArray[0]["group_name"] + "</h2></div><div class='panel-body'><span>Categorie: <span class='title'>" + groupArray[0]["group_type"] + "</span></span><br/><span class='membrii'>" + (member_count == 1 ? member_count + " membru" : member_count + " membri") + "</span><br/><span>Fondat pe: " + ConvertUnixTimeStamp(groupArray[0]["founded"].ToString()) + "</span><br/></div></div>"));
                groupInfo.Controls.Add(grInfo);

                conn.Close();

                showComments();
            }

        }

        public static DateTime? ConvertUnixTimeStamp(string unixTimeStamp)
        {
            return new DateTime(1970, 1, 1).AddSeconds(Convert.ToDouble(unixTimeStamp) + 3600*2);
        }

        public DataRow[] showComments()
        {
            String id = Request.QueryString["id"];
            if (id != null)
            {
                String connString = System.Configuration.ConfigurationManager.ConnectionStrings["GroupsConnString"].ToString();
                conn = new MySql.Data.MySqlClient.MySqlConnection(connString);

                conn.Open();
                queryStr = "SELECT gc.* FROM app_groups.group_comments gc WHERE gc.id_group = " + id;
                cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);

                msg.Load(reader = cmd.ExecuteReader());
                msgArray = msg.AsEnumerable().ToArray();
                reader.Close();

                Response.Write(msgArray[0]["comment"]);

                /*Panel grComments = new Panel();
                grComments.Controls.Add(new LiteralControl(""));
                groupInfo.Controls.Add(grComments);*/
            }

            return msgArray;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

创建一个新类dataAccess.cs

using System;
using System.Data;

namespace Groups
{
    public class dataAccess
    {
        public List<string> GetComments()
        {
            String connString = System.Configuration.ConfigurationManager.ConnectionStrings["GroupsConnString"].ToString();
            conn = new MySql.Data.MySqlClient.MySqlConnection(connString);

            try
            {
                MySql.Data.MySqlClient.MySqlDataReader reader;
                DataTable msg = new DataTable();
                conn.Open();
                List<string> comments = new List<string>();
                queryStr = "SELECT gc.* FROM app_groups.group_comments gc WHERE gc.id_group = " + id;
                cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);

                msg.Load(reader = cmd.ExecuteReader());
                foreach(DataRow dr in msg.Rows)
                {
                    comments.Add(dr["comment"]);
                }
                reader.Close();
                return comments;
            }
            catch (Exception ex)
            {
                //throw ex;
            }
        }
    }
}

在ASPX页面中

<asp:Panel ID="commentSection" runat="server">
    <%
        var data = Groups.dataAccess.GetComments();
        foreach(string c in data)
        {
            Response.Write("<p>" + c + "</p>");
        }
    %>
</asp:Panel>

答案 1 :(得分:0)

根据ASP.NET页面生命周期,您的方法showComments()将在<%= msgArray[0]["comment"] %>部分之后调用。因此它将无法在那里使用。 最好的方法是在.aspx页面中使用Label之类的控件,并从showComments()方法更新文本属性。