【问题标题】:grid view is not showing result网格视图未显示结果
【发布时间】:2011-04-13 06:45:43
【问题描述】:

我想在运行时绑定DataSource 987654322 @,当用户从DropDownList中选择一个选项时。但所选表或连接未正确建立。 请检查以下代码并给我适当的解决方案。

    public partial class index : System.Web.UI.Page
    {
        SqlConnection conn = new SqlConnection();
        string option = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            option = selectProductdropdown.SelectedValue;
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Label2.Text = option;
            if (option == "Books")
            {

                Label3.Text = option;
                conn.ConnectionString = ConfigurationManager.ConnectionStrings["booksconnectionstring"].ConnectionString;
                conn.Open();
                SqlCommand cmd = new SqlCommand("SELECT * from books", conn);
                cmd.CommandType = CommandType.Text;

                SqlDataAdapter reader = new SqlDataAdapter(cmd);

                DataSet s = new DataSet();
                reader.Fill(s);
                GridView1.DataSource = s;
                GridView1.DataBind();
                conn.Close();
            }

【问题讨论】:

  • 你能把你的错误信息放在这里吗?

标签: c# asp.net sql gridview drop-down-menu


【解决方案1】:

问题出在您的 page_load 事件中,您在其中为选项分配了一个值。当您单击按钮时,page_load 将再次调用,您的值将重置。

应该是……

 protected void Page_Load(object sender, EventArgs e)
    {
       if(!Page.IsPostBack)
        option = selectProductdropdown.SelectedValue;
    }

如果你喜欢的话会更好..

if (selectProductdropdown.SelectedValue == "Books")

【讨论】:

    【解决方案2】:

    因为您可能会在每次页面加载时清空选项。

    【讨论】:

      【解决方案3】:

      避免使用公共变量string option = "";

      而是在 Click Event 中定义相同的值并在那里获取选定的值

      option = selectProductdropdown.SelectedValue;// move to click event
      

      因为当按钮被点击时,下拉菜单会被重置(假设你没有在这里显示下拉绑定代码)

      【讨论】:

      • 我将其移至按钮单击事件。但仍然没有显示结果。
      【解决方案4】:
      protected void Page_Load(object sender, EventArgs e)
      {
          if (!Page.IsPostBack)
              option = selectProductdropdown.SelectedValue;
      }
      

      【讨论】:

        【解决方案5】:

        你省略了这一行:

        cmd.ExecuteReader();
        

        把它放在语句之间,像这样:

        SqlCommand cmd = new SqlCommand("SELECT * from books", conn);
        cmd.ExecuteReader();  // <-- HERE
        cmd.CommandType = CommandType.Text;
        

        【讨论】:

          猜你喜欢
          • 2014-04-14
          • 2019-03-09
          • 2013-02-18
          • 1970-01-01
          • 1970-01-01
          • 2014-02-07
          • 1970-01-01
          • 2021-09-24
          • 1970-01-01
          相关资源
          最近更新 更多