CSDN博客

img bccu

DataGrid的使用:(一)、在DataGrid控件中实现基本的操作(编辑、删除、分页)

发表于2004/10/15 18:24:00  1116人阅读

  //使DataGrid的当前行变为编辑状态
private void DataGrid1_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
  {
   this.DataGrid1.EditItemIndex =e.Item.ItemIndex;
   this.bindgrid ();
  }

//撤消所作的修改时使用(点击取消按钮时触发) 
 private void DataGrid1_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
  {
   this.DataGrid1.EditItemIndex =-1;
   this.bindgrid ();
  }

//  删除当前行时使用(点击删除按钮时触发)
private void DataGrid1_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
  {
   int userid=(int)this.DataGrid1.DataKeys[e.Item.ItemIndex];
           
   string SQLStatement="Delete xtuser WHERE user_id="+userid;
   SqlConnection myConnection = new SqlConnection(strcon);
   SqlCommand myCommand = new SqlCommand (SQLStatement,myConnection);            
            
   myCommand.CommandTimeout = 15;
   myCommand.CommandType=CommandType.Text;

   try
   {
    myConnection.Open();
    myCommand.ExecuteNonQuery();
    myConnection.Close();
   }
   catch(Exception ee)
   {
    throw ee;
   }
   this.DataGrid1.EditItemIndex = -1;
//   ds.Tables["user"].Rows.Clear ();
   ds.Tables[0].Clear ();
   this.sqlDataAdapter1 .Fill (ds,"user");
   this.bindgrid();            
  }

 //点击页码时触发,用于简单的分页  
private void DataGrid1_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
  {
   this.DataGrid1.CurrentPageIndex =e.NewPageIndex ;
   this.bindgrid ();
  }

//修改完毕之后,点击更新按钮触发,达到修改的目的
  private void DataGrid1_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
  {
   int userid=(int)this.DataGrid1.DataKeys[e.Item.ItemIndex];
            string usernc=((TextBox)e.Item.Cells[1].Controls[0]).Text;
   string usermc=((TextBox)e.Item.Cells[2].Controls[0]).Text;
  
   string SQLStatement="UPDATE  xtuser "+
    "SET  user_nc='"+usernc+"', "+
    "user_mc='"+usermc+"'"+
    " WHERE userid ="+userid;

   SqlConnection myConnection = new SqlConnection(this.strcon); 
   SqlCommand myCommand = new SqlCommand(SQLStatement,myConnection);            
            
   myCommand.CommandTimeout = 15;
   myCommand.CommandType = CommandType.Text;        

   try
   {
    myConnection.Open();
    myCommand.ExecuteNonQuery();
    myConnection.Close();
   }
   catch(Exception ee)
   {
    throw ee ;
   }

   MyDataGrid.EditItemIndex = -1;
   this.bindgrid();
  }


将数据绑定到DataGrid上
 private void bindgrid()
  {
   this.DataGrid1.DataSource=ds.Tables["user"].DefaultView ;
   this.DataGrid1.DataBind ();
  }

阅读全文
0 0

相关文章推荐

img
取 消
img