我开始设置数据库表的pid字段不是主键而且也不是自动增长,DataGrid就可以排序。现在我把pid字段设置成主键并且是自动增长,DataGrid就不能自动排序了,请大家帮忙看看,一下是代码:<asp:datagrid id="DGPatent" runat="server" Width="1123px" Height="40px" AutoGenerateColumns="False"
AllowPaging="True" AllowSorting="True" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" GridLines="Vertical" ForeColor="Black" PageSize="20">
<SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#CE5D5A"></SelectedItemStyle>
<AlternatingItemStyle BackColor="White"></AlternatingItemStyle>
<ItemStyle BackColor="#F7F7DE"></ItemStyle>
<HeaderStyle Font-Bold="True" ForeColor="White" BackColor="#6B696B"></HeaderStyle>
<FooterStyle BackColor="#CCCC99"></FooterStyle>
<Columns>
<asp:BoundColumn DataField="pid" SortExpression="pid" HeaderText="专利序号"></asp:BoundColumn>
<asp:BoundColumn DataField="pno" HeaderText="专利号"></asp:BoundColumn>
<asp:HyperLinkColumn Target="_blank" DataNavigateUrlField="pid" DataNavigateUrlFormatString="searchcontent.aspx?pid={0}"
DataTextField="pname" HeaderText="专利名称"></asp:HyperLinkColumn>
<asp:BoundColumn DataField="type" SortExpression="type" HeaderText="专利类别"></asp:BoundColumn>
<asp:BoundColumn DataField="state" SortExpression="state" HeaderText="专利状态"></asp:BoundColumn>
<asp:BoundColumn DataField="oprginator" HeaderText="发明人或参加人"></asp:BoundColumn>
<asp:BoundColumn DataField="pdate" SortExpression="pdate" HeaderText="申请日期"></asp:BoundColumn>
<asp:BoundColumn DataField="adate" HeaderText="授权日期"></asp:BoundColumn>
<asp:BoundColumn DataField="abdate" HeaderText="废止日期"></asp:BoundColumn>
<asp:BoundColumn DataField="ptime" HeaderText="保护期限"></asp:BoundColumn>
<asp:BoundColumn DataField="proposer" HeaderText="专利申请人"></asp:BoundColumn>
<asp:BoundColumn DataField="country" HeaderText="专利国别"></asp:BoundColumn>
<asp:BoundColumn DataField="unit" HeaderText="授权单位"></asp:BoundColumn>
<asp:BoundColumn DataField="re" HeaderText="备注"></asp:BoundColumn>
</Columns>
<PagerStyle NextPageText="上一页" PrevPageText="下一页" HorizontalAlign="Center" ForeColor="Black"
BackColor="#F7F7DE" Mode="NumericPages"></PagerStyle>
</asp:datagrid>

解决方案 »

  1.   

    cs代码:
    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.SessionState;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using System.Data.SqlClient;
    namespace patent
    {
    /// <summary>
    /// patentSearch 的摘要说明。
    /// </summary>
    public class patentSearch : System.Web.UI.Page
    {
    protected System.Web.UI.WebControls.Label Lstr;
    protected System.Web.UI.WebControls.Label Label1;
    protected System.Web.UI.WebControls.TextBox txtpno;
    protected System.Web.UI.WebControls.Label Label2;
    protected System.Web.UI.WebControls.TextBox txtpname;
    protected System.Web.UI.WebControls.Label Label3;
    protected System.Web.UI.WebControls.DropDownList ddlpstate;
    protected System.Web.UI.WebControls.Label Label4;
    protected System.Web.UI.WebControls.TextBox txtkey;
    protected System.Web.UI.WebControls.DataGrid DGPatent;
    protected System.Web.UI.WebControls.ImageButton btnSelect;
    protected System.Web.UI.WebControls.ImageButton btnExcel;
    protected System.Web.UI.WebControls.ImageButton btnNew;
    protected System.Web.UI.HtmlControls.HtmlTable Table1;

    private void Page_Load(object sender, System.EventArgs e)
    {
    // 在此处放置用户代码以初始化页面
    if(!IsPostBack)
    {
    ViewState["Direction"] = "ASC";
    BindGrid(string.Empty);
    } DGPatent.DataSource=ClsDB.ExecuteQueryToDataSet("select * from patentInfo");
    DGPatent.DataBind();
    } private void BindGrid(string str)
    {
    SqlConnection cn = new SqlConnection("server=192.168.16.245;uid=sa;pwd=sa;database=patent");
    string strSQL = string.Empty;
    if (str == string.Empty)
    strSQL = "select * from patentInfo order by pid asc";
    else
    strSQL = "select * from patentInfo order by " + str + " " + ViewState["Direction"].ToString();
    SqlDataAdapter da = new SqlDataAdapter(strSQL , cn);
    DataSet ds = new DataSet();
    cn.Open();
    da.Fill(ds);
    cn.Close();
    DGPatent.DataSource = ds;
    DGPatent.DataKeyField = "pid";
    DGPatent.DataBind(); }
    private void DGPatent_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
    {
    if (ViewState["Direction"].ToString() == "ASC")
    ViewState["Direction"] = "DESC";
    else
    ViewState["Direction"] = "ASC";
    BindGrid(e.SortExpression);
    }
    #region Web 窗体设计器生成的代码
    override protected void OnInit(EventArgs e)
    {
    //
    // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
    //
    InitializeComponent();
    base.OnInit(e);
    }

    /// <summary>
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改
    /// 此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {    
    this.btnSelect.Click += new System.Web.UI.ImageClickEventHandler(this.btnSelect_Click);
    this.btnExcel.Click += new System.Web.UI.ImageClickEventHandler(this.btnExcel_Click);
    this.btnNew.Click += new System.Web.UI.ImageClickEventHandler(this.btnNew_Click);
    this.DGPatent.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.DGPatent_PageIndexChanged);
    this.Load += new System.EventHandler(this.Page_Load); }
    #endregion private void btnSelect_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
    if(this.txtpno.Text!="")
    {
    string sql="select * from patentInfo where pno like '%" + this.txtpno.Text + "%'";

    DGPatent.DataSource=ClsDB.ExecuteQueryToDataSet(sql);
    DGPatent.DataBind();
    } if(this.txtpname.Text!="")
    { string sql="select * from patentInfo where pname like '%" + this.txtpname.Text + "%'";

    DGPatent.DataSource=ClsDB.ExecuteQueryToDataSet(sql);
    DGPatent.DataBind();
    } if(this.ddlpstate.SelectedValue!="--请选择--")
    { string sql="select * from patentInfo where state like '%" + this.ddlpstate.SelectedValue + "%'";

    DGPatent.DataSource=ClsDB.ExecuteQueryToDataSet(sql);
    DGPatent.DataBind();
    } if(this.txtkey.Text!="")
    {

    string sql="select * from patentInfo where pno like '%" + this.txtkey.Text + "%' or pname like'%"+ this.txtkey.Text +"%' or iname like '%" + txtkey.Text + "%' or unit like '%" + txtkey.Text + "%' or oprginator like '%" + txtkey.Text + "%' or re like '%" + txtkey.Text + "%'";
    DGPatent.DataSource=ClsDB.ExecuteQueryToDataSet(sql);
    DGPatent.DataBind();
    }
    } private void btnExcel_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
    DGPatent.AllowSorting=false;//设置不能排序
    DGPatent.AllowPaging=false;//设置不能分页
    DGPatent.DataBind ();//绑定数据
    Response.Clear(); 
       Response.Buffer= true; 
       Response.Charset="utf-8";
    string FileFlow = DateTime.Now.ToShortDateString();   
       Response.AppendHeader("Content-Disposition","attachment;filename="+FileFlow+".xls"); 
       Response.ContentEncoding=System.Text.Encoding.GetEncoding("utf-8");   
       Response.ContentType = "application/ms-excel"; 
       this.EnableViewState = false;  
        System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); 
       System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
        DGPatent.RenderControl(oHtmlTextWriter );    
       Response.Write(oStringWriter.ToString()); 
       Response.End(); 
    } private void btnNew_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
    //string sql="select username from userInfo where id=1";
    //ClsDB.ExecuteQuery(sql);
    //Response.Write(sql);
    //if(ClsDB.ExecuteQuery(sql)=="zytian")
    //{
    Response.Redirect("patentInfo.aspx");
    //}
    //else
    //{
    // Response.Write("<script>alert('对不起,你没有此项操作的权力!')</script>");
    //}

    } private void DGPatent_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
    {
    DGPatent.CurrentPageIndex=e.NewPageIndex;
    DGPatent.DataBind();
    }
    }
    }
      

  2.   

    排序的没看出来哪错了.分页的有点问题-_-!
    private void DGPatent_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
            {
                DGPatent.CurrentPageIndex=e.NewPageIndex;
                DGPatent.DataBind();//这写的不对,应该调你绑定数据的方法
            }
      

  3.   


    主键和自动标识应该不影响排序吧。我代码里查询条件好像都是pid。
      

  4.   

    private void Page_Load(object sender, System.EventArgs e)
            {
                // 在此处放置用户代码以初始化页面
                if(!IsPostBack)
                {
                    ViewState["Direction"] = "ASC";
                    BindGrid(string.Empty);
                }            //这两行代码有问题.因为这个所以把你的排序冲没了..这两行代码每次postback都会执行的.这样的话.你BindGrid()方法就没用了
                DGPatent.DataSource=ClsDB.ExecuteQueryToDataSet("select * from patentInfo");
                DGPatent.DataBind();    
            }
      

  5.   

    private void btnNew_Click(object sender, System.Web.UI.ImageClickEventArgs e)
            {
                string sql="select username from userInfo where id=1";
                ClsDB.ExecuteQuery(sql);
                Response.Write(sql);
                if(ClsDB.ExecuteQuery(sql).Equals("zytian"))
                {
                    Response.Redirect("patentInfo.aspx");
                }
                else
                {
                   Response.Write("<script>alert('对不起,你没有此项操作的权力!')</script>");
                }
            }
    红色显示的地方这么写对吗?? userInfo表字段:id主键:自动增长,int,not null  ; username nvarchar(50)
    我想单击btnNew按钮的时候看看这个用户是否有权限访问patentInfo.aspx页面。
      

  6.   

    你这个排序的确有问题,你没有保存查询条件,当点击查询的时候把this.txtpno.Text 的值保存下来,排序的那个函数里要加上这个搜索的条件的,不然一排序结果就变了.帮你大概的修改了一下,具体细节还要你自己完善.private void Page_Load(object sender, System.EventArgs e)
    {
    // 在此处放置用户代码以初始化页面
    if(!IsPostBack)
    {
    ViewState["Direction"] = "ASC";
    ViewState["strWhere"]="";//保存查询条件
    BindGrid(string.Empty);
    } DGPatent.DataSource=ClsDB.ExecuteQueryToDataSet("select * from patentInfo");
    DGPatent.DataBind();    
    }
    private void BindGrid(string str)
    {
    SqlConnection cn = new SqlConnection("server=192.168.16.245;uid=sa;pwd=sa;database=patent");
    string strSQL = string.Empty;
    if (str == string.Empty)
    strSQL = "select * from patentInfo "+ViewState["strWhere"]+" order by pid asc";
    else
    strSQL = "select * from patentInfo "+ViewState["strWhere"]+" order by " + str + " " + ViewState["Direction"].ToString();
    SqlDataAdapter da = new SqlDataAdapter(strSQL , cn);
    DataSet ds = new DataSet();
    cn.Open();
    da.Fill(ds);
    cn.Close();
    DGPatent.DataSource = ds;
    DGPatent.DataKeyField = "pid";
    DGPatent.DataBind(); } private void btnSelect_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
    //下面做了部分调整,不知道你书不是这个意思.
    string sql="select * from patentInfo ";
    string strWhere=" where 1=1 ";
    if(this.txtpno.Text!="")
    {
    strWhere+=" and pno like '%" + this.txtpno.Text + "%'";
    } if(this.txtpname.Text!="")
    { strWhere+=" and pname like '%" + this.txtpname.Text + "%'";
    } if(this.ddlpstate.SelectedValue!="--请选择--")
    { strWhere+=" and state like '%" + this.ddlpstate.SelectedValue + "%'";   
    } if(this.txtkey.Text!="")
    {
                    
    strWhere+=" and pno like '%" + this.txtkey.Text + "%' or pname like'%"+ this.txtkey.Text +"%' or iname like '%" + txtkey.Text + "%' or unit like '%" + txtkey.Text + "%' or oprginator like '%" + txtkey.Text + "%' or re like '%" + txtkey.Text + "%'";
            }
    DGPatent.DataSource=ClsDB.ExecuteQueryToDataSet(sql);
    DGPatent.DataBind();
    ViewState["strWhere"]=strWhere;//保存查询条件
    }
      

  7.   

    自己解决了。原因很菜,DataGrid的SortCommand事件没有选择DGpatent_SortCommand()。就是因为这个原因。我以前选上了啊。不知道什么时候自己就跑掉了。可能是我不经意之间按CTRL+Z给撤销了。所以说做事情要认真仔细。很感谢潇湘夜雨当爱已成往事的帮助。谢谢啦。
      

  8.   

    这个不能怪你了,vs2003有这个BUG,经常无缘无故的丢失事件,以前经常遇到.建议升升版本,至少也用个2005吧