关闭

编辑DataGrid控件(二)

标签: datagridtextboxdatasetaspobjectborder
939人阅读 评论(0) 收藏 举报
分类:

上一章我们就DataGrid控件的就地编辑进行详细的讨论,你也许会抱怨DataGrid控件的就地编辑有很多的不足,比如:不能编辑Employee Name的模板列,比如对编辑的列不能使用选择列表等等的问题。是的,上一章的就地编辑是DataGrid控件最简单也是最基础的介绍,如果你看了本章的内容,对上一章的还存在的抱怨就会少一些。下面各章是对前面的不断的补充,请继续关注!

本章我们将介绍:用模板进行就地编辑。 

那是如何实现的呢,请向下看:

Edit2.aspx

 <!--DataKeyField="EmployeeID"为指定表的主键 -->
<asp:datagrid id="DataGrid1" DataKeyField="EmployeeID" Font-Size="12px" Font-Name="Verdana" BorderWidth="1px"
    BorderStyle="Solid" BorderColor="black" AutoGenerateColumns="False" CellSpacing="0" CellPadding="2"
    Runat="server">
    <HeaderStyle BackColor="brown" />
    <AlternatingItemStyle BackColor="palegoldenrod" />
    <ItemStyle BackColor="beige"></ItemStyle>
    <Columns>
     <asp:BoundColumn DataField="EmployeeID" HeaderText="ID" ReadOnly="True" />
     <asp:TemplateColumn HeaderText="Employee Name">
                                         <!-- 模板列的设置 --> 
      <ItemTemplate>
       <%#DataBinder.Eval(Container.DataItem,"TitleOfCourtesy")+"<b>"+
        DataBinder.Eval(Container.DataItem,"FirstName")+"</b>"+
        DataBinder.Eval(Container.DataItem,"LastName")%>
      </ItemTemplate>
                                          <!-- 模板列编辑项的设置 -->
          <EditItemTemplate>
       <asp:DropDownList Runat=server ID=ddTitles Width=50px DataSource='<%#aTitleOfCourtesy %>' />
       <asp:TextBox Runat=server ID=txtFirstName Width=80px Text='<%#DataBinder.Eval(Container.DataItem,"FirstName")%>' />
       <asp:TextBox Runat=server ID=txtLastName Width=100px Text='<%#DataBinder.Eval(Container.DataItem,"LastName")%>' />
      </EditItemTemplate>
     </asp:TemplateColumn>
     <asp:BoundColumn DataField="title" HeaderText="Position" />
     <asp:BoundColumn DataField="Country" HeaderText="From" />
                                        <!-- 在这里对编辑列用图像来替代文本 -->
     <asp:EditCommandColumn ButtonType="LinkButton" EditText='<img src=Images/edit.gif border=0 align=middle>'
      CancelText='<img src=images/cancel.gif border=0 align=middle alt=Cancel>' UpdateText='<img src=images/ok.gif  border=0 align=middle alt=ok>'>
                                          <!-- 在这里对编辑列的风格进行设置 -->
      <ItemStyle BackColor="lightblue" Width="15px" />
     </asp:EditCommandColumn>
    </Columns>
   </asp:datagrid>


Edit2.aspx.cs:
private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
   if (!Page.IsPostBack)
   {
    OnDataLoad();
   }
  }
               

                //将表中的记录fill到DataSet中,并将其绑定到DataGrid控件中
  private void OnDataLoad()
  {
          SqlConnection cn=new SqlConnection("DATABASE=Northwind;SERVER=localhost;UID=sa;PWD=;");
    string strsql="SELECT employeeid, titleofcourtesy, firstname, lastname, title, country FROM Employees";
    SqlDataAdapter da=new SqlDataAdapter(strsql,cn);
    DataSet ds=new DataSet();
    da.Fill(ds,"MyTable");
    DataGrid1.DataSource=ds.Tables["MyTable"];
    DataGrid1.DataBind();
  }

              private void DataGrid1_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
  {
    DataGrid1.EditItemIndex=e.Item.ItemIndex;
    OnDataLoad();
  }

  private void DataGrid1_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
  {
   DataGrid1.EditItemIndex=-1;
   OnDataLoad();
  }

  private void DataGrid1_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
  {
   int iPosition=2;
   int iFrom=3;
   TextBox txtPosition=(TextBox)e.Item.Cells[iPosition].Controls[0];
   TextBox txtFrom=(TextBox)e.Item.Cells[iFrom].Controls[0];
   TextBox txtFirstName=(TextBox)e.Item.FindControl("txtFirstName");
   TextBox txtLastName=(TextBox)e.Item.FindControl("txtLastName");
   DropDownList ddTitles=(DropDownList)e.Item.FindControl("ddTitles");

   StringBuilder sb=new StringBuilder();
   sb.Append("Update Employees set ");
   sb.Append("
TitleOfCourtesy=@TitleOfCourtesy,FirstName=@FirstName,");
   sb.Append("
LastName=@LastName,Title=@Title,Country=@Country ");
   sb.Append("where
EmployeeID=@EmployeeID");
   SqlConnection cn=new SqlConnection("DATABASE=Northwind;SERVER=localhost;UID=sa;PWD=;");
   SqlCommand cmd=new SqlCommand(sb.ToString(),cn);

            SqlParameter p1=new SqlParameter("@EmployeeID",SqlDbType.Int);
   p1.Direction=ParameterDirection.Input;
   p1.Value=DataGrid1.DataKeys[e.Item.ItemIndex];
   cmd.Parameters.Add(p1);
  
   SqlParameter p2=new SqlParameter("@TitleOfCourtesy",SqlDbType.NVarChar,25);
   p2.Direction=ParameterDirection.Input;
   p2.Value=ddTitles.SelectedItem.Text;
   cmd.Parameters.Add(p2);

   SqlParameter p3=new SqlParameter("@FirstName",SqlDbType.NVarChar,10);
   p3.Direction=ParameterDirection.Input;
   p3.Value=txtFirstName.Text;
   cmd.Parameters.Add(p3);

   SqlParameter p4=new SqlParameter("@LastName",SqlDbType.NVarChar,20);
   p4.Direction=ParameterDirection.Input;
   p4.Value=txtLastName.Text;
   cmd.Parameters.Add(p4);

   SqlParameter p5=new SqlParameter("@Title",SqlDbType.NVarChar,30);
   p5.Direction=ParameterDirection.Input;
   p5.Value=txtPosition.Text;
   cmd.Parameters.Add(p5);

            SqlParameter p6=new SqlParameter("@Country",SqlDbType.NVarChar,15);
   p6.Direction=ParameterDirection.Input;
   p6.Value=txtFrom.Text;
   cmd.Parameters.Add(p6);

   cn.Open();
   cmd.ExecuteNonQuery();
   cn.Close();

   DataGrid1.EditItemIndex=-1;
   OnDataLoad();
  }

                //点击编辑图像时,这里会有一个反常之处:在下拉列表中所选择的项与雇员的信息不匹配,所以要在这里初始化编辑模板
                //中的子控件状态
  private void DataGrid1_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
  {
   ListItemType lItem=e.Item.ItemType;
   if (lItem==ListItemType.EditItem)
   {
    DropDownList ddTitles=(DropDownList)e.Item.FindControl("ddTitles");
    DataRowView dr=(DataRowView)e.Item.DataItem;
    if (dr!=null)
    {
     ddTitles.SelectedIndex=Array.IndexOf(aTitleOfCourtesy,dr["titleofcourtesy"].ToString());
    }
   }
  }

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:114476次
    • 积分:2008
    • 等级:
    • 排名:第19180名
    • 原创:74篇
    • 转载:37篇
    • 译文:2篇
    • 评论:2条