ASP.NET 當GridView中沒有數據的時候,顯示標題欄 並且給出一行數據提


方法一:直接改GridView的屬性(簡單方法)

顯示標題欄:ShowHeaderWhenEmpty:True

給出文本提示:EmptyDataText:沒有您查找的數據

方法二:

private void GetData()
    {
        using (SqlConnection sqlcnn=new SqlConnection(sqlstr))
        {
            using (SqlCommand sqlcmm=sqlcnn.CreateCommand())
            {
                sqlcmm.CommandText = "select * from Users";
                DataTable dt = new DataTable();
                SqlDataAdapter adapter = new SqlDataAdapter(sqlcmm);
                adapter.Fill(dt);
                if (dt.Rows.Count > 0)   //當數據庫有數據的時候綁定數據
                {
                    this.GridView1.DataSource = dt;
                    this.GridView1.DataBind();
                }
                else     //當數據庫沒有數據的時候,顯示一行文本給用戶一個提示,並且顯示出標題行來
                {
                    DataRow row = dt.NewRow();
                    dt.Rows.Add(row);
                    this.GridView1.DataSource = dt;
                    this.GridView1.DataBind();
                }
            }
        }
    }

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //當數據庫沒有數據的時候,執行以下操作
        if (this.GridView1.Rows.Count < 1)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                for (int i = 3; i > 0; i--)   //移除除第一個以外的所有單元格
                {
                    e.Row.Cells.RemoveAt(i);
                }
                e.Row.Cells[0].ColumnSpan = 4; //把第一個單元格同后幾個單元格合並
                e.Row.Cells[0].Text = "數據庫沒有數據";   //提示語
                e.Row.Cells[0].HorizontalAlign = HorizontalAlign.Center;   //文本居中
            }
        }
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM