DataGrid颜色交替,删除确认,添加一个从1开始的递增列

    技术2022-05-11  10

    private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)  {   if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)    {    //颜色交替       e.Item.Attributes.Add("onmouseover","this.style.backgroundColor='#fff7ce'");     if(e.Item.ItemType == ListItemType.Item)     {      e.Item.Attributes.Add("onmouseout", "this.style.backgroundColor='#ffffff'");     }

        if(e.Item.ItemType ==ListItemType.AlternatingItem)     {      e.Item.Attributes.Add("onmouseout", "this.style.backgroundColor='seashell'");     }    }   }

     

    删除确认:right click DataGrid1-->“属性生成器”-->添加“删除”按纽列-->在“文本(T)"中写

    <div   id="del"   οnclick="JavaScript:return   confirm('确定删除吗?')">删除</div>

    添加删除事件

    private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)  {   if(e.CommandName == "Delete")   {    int index = Int32.Parse(DataGrid1.DataKeys[e.Item.ItemIndex].ToString());    DeleteRecord(index);    GetAllAssets();//重新绑定数据   }  }

     

    添加一个递增的数字列:  

    <asp:BoundColumn DataField="RowNumber" HeaderText="序号"></asp:BoundColumn>

    在加载数据时添加创建递增列:

    /// <summary>  /// 加载数据,绑定到DataGrid  /// </summary>  private void LoadData()  {   string strCmd = "";   if(Session["sorting"] == null)   {    strCmd = "SELECT * FROM Jxt_DeviceManage_DeviceBasicData";   }   else   {    strCmd = "SELECT * FROM Jxt_DeviceManage_DeviceBasicData ORDER BY "+Session["sorting"].ToString()+" "+Session["sortDirection"].ToString();   }   conn = new SqlConnection(strConn);   adapter = new SqlDataAdapter(strCmd,conn);   ds = new DataSet();   adapter.Fill(ds);   DataTable dt = ds.Tables[0];   DataColumn dataCol = new DataColumn("RowNumber",Type.GetType("System.Int16"));   dt.Columns.Add(dataCol);   for(int i=0;i<dt.Rows.Count;i++)   {    if(0 == i)    {     dt.Rows[i][dataCol] = 1;    }    else    {     dt.Rows[i][dataCol] = Convert.ToInt16(dt.Rows[i-1][dataCol])+1;    }   }   DataView dv = new DataView(dt);   DataGrid1.DataSource = dv;   DataGrid1.DataKeyField = "DBID";   this.DataGrid1.DataBind();   if(this.DataGrid1.Items.Count < 1)   {    this.DataGrid1.Visible = false;    Response.Write("没有任何设备");   }  }


    最新回复(0)