DataGrid编辑操作(加入下拉框)

该博客展示了使用C#和数据库进行DataGrid操作的示例。包含HTML页面代码和后置C#代码,实现了数据的显示、分页、排序、编辑和更新等功能,还给出了不用ViewState保存下拉选框值的方法。

HTML::

<%@ Page language="c#" Codebehind="DGSorting.aspx.cs" AutoEventWireup="false" Inherits="DataGridOperate.DGSorting" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>DGSorting</title>
  <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
  <meta content="C#" name="CODE_LANGUAGE">
  <meta content="JavaScript" name="vs_defaultClientScript">
  <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
 </HEAD>
 <body MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server">
   <asp:datagrid id="DataGrid1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False"
    DataKeyField="ID">
    <Columns>
     <asp:EditCommandColumn ButtonType="PushButton" UpdateText="更新" HeaderText="操作" CancelText="取消" EditText="编辑"></asp:EditCommandColumn>
     <asp:BoundColumn DataField="ID" ReadOnly="True" HeaderText="编号"></asp:BoundColumn>
     <asp:BoundColumn DataField="Name" SortExpression="Name" HeaderText="姓名"></asp:BoundColumn>
     <asp:TemplateColumn HeaderText="性别">
      <ItemTemplate>
       <asp:Label ID="lblSex" Runat="server" Text='<%# DataBinder.Eval(Container,"DataItem.Sex").ToString() %>'>
       </asp:Label>
      </ItemTemplate>
      <EditItemTemplate>
       <asp:CheckBox ID="chkSex" Runat="server"></asp:CheckBox>
      </EditItemTemplate>
     </asp:TemplateColumn>
     <asp:BoundColumn DataField="Tel" HeaderText="电话"></asp:BoundColumn>
     <asp:TemplateColumn>
      <HeaderTemplate>
       <asp:Button id="btnSort" Text="薪资" Runat="server" CommandName="sort" CommandArgument="Salary"></asp:Button>
      </HeaderTemplate>
      <ItemTemplate>
       <asp:Label id=lblSalary Text='<%# DataBinder.Eval(Container,"DataItem.Salary").ToString() %>' Runat="server">
       </asp:Label>
      </ItemTemplate>
     </asp:TemplateColumn>
     <asp:TemplateColumn HeaderText="部门">
      <ItemTemplate>
       <asp:Label ID="Label1" Runat="server" Text='<%# DataBinder.Eval(Container,"DataItem.Depart").ToString() %>'>
       </asp:Label>
      </ItemTemplate>
      <EditItemTemplate>
       <asp:DropDownList ID="ddlDepart" Runat="server"></asp:DropDownList>
      </EditItemTemplate>
     </asp:TemplateColumn>
    </Columns>
    <PagerStyle Mode="NumericPages"></PagerStyle>
   </asp:datagrid></form>
 </body>
</HTML>


后置代码:
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 DataGridOperate
{
 /// <summary>
 /// DGSorting 的摘要说明。
 /// </summary>
 public class DGSorting : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.DataGrid DataGrid1;

  protected DataSet dsEmployee = new DataSet();
 
  private void Page_Load(object sender, System.EventArgs e)
  {
   if(!Page.IsPostBack)
   {
    this.Admin();
   }
  }

  private void Admin()
  {
   SqlConnection Conn = new SqlConnection("server=.;database=test;uid=sa");

   string strSQL = "select * from salary";

   SqlDataAdapter adapter = new SqlDataAdapter(strSQL,Conn);

   adapter.Fill(dsEmployee);

   this.DataGrid1.DataSource = dsEmployee;
   this.DataGrid1.DataBind();
  
   this.ViewState["source"] = dsEmployee;
  }
  private void DataGrid1_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
  {
   this.DataGrid1.EditItemIndex = -1;
   this.Admin();  
  }

  private void DataGrid1_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
  {
   this.ViewState["Sex"] = ((Label)e.Item.Cells[3].FindControl("lblSex")).Text;
   this.ViewState["Depart"] = ((Label)e.Item.Cells[3].FindControl("Label1")).Text;
   this.DataGrid1.EditItemIndex = e.Item.ItemIndex;
   this.Admin();  

  }

  private void DataGrid1_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
  {
   SqlConnection Conn = new SqlConnection("server=.;database=test;uid=sa");
   string strSQL = "update salary set name=@name,sex=@sex,tel=@tel,salary=@salary,depart=@depart where id=@id";

   SqlCommand Comm = new SqlCommand(strSQL,Conn);

   Comm.Parameters.Add(new SqlParameter("@name",System.Data.SqlDbType.VarChar,16));
   Comm.Parameters.Add(new SqlParameter("@sex",System.Data.SqlDbType.Bit,1));
   Comm.Parameters.Add(new SqlParameter("@tel",System.Data.SqlDbType.VarChar,50));
   Comm.Parameters.Add(new SqlParameter("@salary",System.Data.SqlDbType.Int,4));
   Comm.Parameters.Add(new SqlParameter("@depart",System.Data.SqlDbType.VarChar,12));
   Comm.Parameters.Add(new SqlParameter("@id",System.Data.SqlDbType.Int,4));
   
   Comm.Parameters["@id"].Value = this.DataGrid1.DataKeys[e.Item.ItemIndex];
   
   Comm.Parameters["@name"].Value = ((TextBox)e.Item.Cells[2].Controls[0]).Text;
   Comm.Parameters["@sex"].Value = ((CheckBox)e.Item.Cells[3].FindControl("chkSex")).Checked;
   Comm.Parameters["@tel"].Value = ((TextBox)e.Item.Cells[4].Controls[0]).Text;
   Comm.Parameters["@salary"].Value = ((TextBox)e.Item.Cells[5].Controls[0]).Text;
   Comm.Parameters["@depart"].Value = ((DropDownList)e.Item.Cells[6].FindControl("ddlDepart")).SelectedItem.Text;

   Comm.Connection.Open();
   Comm.ExecuteNonQuery();
   Comm.Connection.Close();

   this.DataGrid1.EditItemIndex = -1;

   this.Admin();
  }

  private DataView GetSource()
  {
   
   SqlConnection Conn = new SqlConnection("server=.;database=test;uid=sa");

   string strSQL = "select * from depart";

   SqlDataAdapter adapter = new SqlDataAdapter(strSQL,Conn);

   DataSet ds = new DataSet();
   adapter.Fill(ds);

   DataView dv = ds.Tables[0].DefaultView;
   
   return dv;

  }

  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.DataGrid1.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.DataGrid1_PageIndexChanged);
   this.DataGrid1.CancelCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_CancelCommand);
   this.DataGrid1.EditCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_EditCommand);
   this.DataGrid1.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.DataGrid1_SortCommand);
   this.DataGrid1.UpdateCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_UpdateCommand);
   this.DataGrid1.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemDataBound);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  private void DataGrid1_SortCommand(object source, DataGridSortCommandEventArgs e)
  {
   DataView dv = ((DataSet)this.ViewState["source"]).Tables[0].DefaultView;

   bool SortAscending = true;

   if(this.ViewState["State"]==null)
   {
    SortAscending = true;
   }
   else
   {
    SortAscending = !bool.Parse(this.ViewState["State"].ToString());
   }
   if(SortAscending)
   {
    dv.Sort = e.SortExpression;
   }
   else
   {
    dv.Sort = e.SortExpression+" DESC";
   }
   this.ViewState["State"] = SortAscending;

   DataGrid1.DataSource = dv;
   DataGrid1.DataBind();
  }

  private void DataGrid1_ItemDataBound(object sender, DataGridItemEventArgs e)
  {
   if(e.Item.ItemType == ListItemType.EditItem)
   {
    DropDownList ddl = (DropDownList)e.Item.FindControl("ddlDepart");

    ddl.DataSource = this.GetSource();
    ddl.DataTextField = "Depart";
    ddl.DataBind();
    ddl.SelectedValue = this.ViewState["Depart"].ToString();

    ((CheckBox)e.Item.Cells[3].FindControl("chkSex")).Checked = bool.Parse(this.ViewState["Sex"].ToString().Trim());
   }

  }

  private void DataGrid1_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
  {
   try
   {
    this.DataGrid1.CurrentPageIndex = e.NewPageIndex ;
   }
   catch
   {
    this.DataGrid1.CurrentPageIndex = 0;
   }
   this.Admin();
  }
 }

---------------------------------------------------------------------------------------------------------------------

可以不用ViewState保存下拉选框中的值
    string str = ((DataSet)DataGrid1.DataSource).Tables[0].Rows[DataGrid1.EditItemIndex]["Depart"].ToString();
    ((DropDownList)(e.Item.FindControl("ddpDepart"))).Items.FindByText(str).Selected = true;

转载于:https://www.cnblogs.com/battler/archive/2005/01/25/96968.html

在 JeeCG Datagrid 中双击行进行编辑时,可以使用 EasyUI 的 ComboGrid 组件来实现下拉框多选。 首先,在需要进行多选的列中使用 ComboGrid 组件,例如: ``` {field:'city',title:'City',width:80,editor:{ type:'combogrid', options:{ panelWidth:400, idField:'id', textField:'text', url:'get_cities.php', multiple:true, columns:[[ {field:'id',title:'ID',width:60}, {field:'text',title:'City Name',width:120}, {field:'country',title:'Country',width:100} ]] } }} ``` 在上面的代码中,我们将一个名为 `city` 的列使用了 ComboGrid 组件,并设置了 `multiple:true` 以启用多选功能。同时,我们也设置了 ComboGrid 组件的 `url` 属性来指定获取下拉框选项的数据源。 接下来,我们需要编写 `get_cities.php` 文件来获取下拉框选项的数据源。在这个文件中,我们可以使用 PHP 代码从数据库中获取城市列表,然后将其以 JSON 格式返回给前端页面。 示例代码: ```php <?php $host = 'localhost'; $user = 'root'; $pass = 'password'; $dbname = 'test'; // Connect to database $conn = mysqli_connect($host, $user, $pass, $dbname); if (!$conn) { die('Could not connect: ' . mysqli_error()); } // Retrieve city list from database $result = mysqli_query($conn, 'SELECT * FROM cities'); // Convert result to JSON format $rows = array(); while ($r = mysqli_fetch_assoc($result)) { $rows[] = $r; } echo json_encode($rows); // Close database connection mysqli_close($conn); ?> ``` 在上面的 PHP 代码中,我们首先连接到数据库,然后从 `cities` 表中获取城市列表,并将其转换为 JSON 格式返回给前端页面。最后,我们关闭数据库连接。 当用户在 JeeCG Datagrid 中双击行进行编辑时,会弹出一个下拉框供用户选择。用户可以通过在下拉框中进行搜索或直接选择多个选项来完成多选操作。用户选择的选项会以逗号分隔的字符串形式保存在 JeeCG Datagrid 中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值