你要DataGrid的edititemindex设置,到当前行,我有代码,下次来我给你,
现在我忙着出门

解决方案 »

  1.   

    datagrid 中有editcommand,deletecommand 等事件!
    在加入相应的代码!
      

  2.   

    <%@ Page Language="C#" %>
    <%@ Import Namespace="System.Data" %>
    <%@ Import Namespace="System.Data.SqlClient" %><html>
    <title>Editing with Templates</title>
    <style>
      a {behavior:url(..\..\mouseover.htc);}
      hr {height:2px;color:black;}
      .StdText {font-family:verdana;font-size:9pt;font-weight:bold;}
      .StdTextBox {font-family:verdana;font-size:9pt;border:solid 1px black;filter:progid:DXImageTransform.Microsoft.dropshadow(OffX=2, OffY=2, Color='gray', Positive='true');}
      .Shadow {filter:progid:DXImageTransform.Microsoft.dropshadow(OffX=2, OffY=2, Color='gray', Positive='true');}
    </style> 
    <script runat="server">
    String [] aTitleOfCourtesy = new String[4] {"Ms.", "Mr.", "Mrs.", "Dr."};
    public void Page_Load(Object sender, EventArgs e)
    {
    // Initialize only the first time...
    if (!Page.IsPostBack)
    {
    lblURL.Text = Request.Url + "<hr>";
    }
    }public void OnLoadData(Object sender, EventArgs e)
    {
    UpdateView();
    }public void ItemCreated(Object sender, DataGridItemEventArgs e)
    { ListItemType lit = e.Item.ItemType;
    if (lit == 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());
    }
    }public void EditCommand(Object sender, DataGridCommandEventArgs e) 
    {
    // Set the current item to edit mode
    grid.EditItemIndex = e.Item.ItemIndex; // Refresh the grid
    UpdateView();
    }
      

  3.   

    public void UpdateCommand(Object sender, DataGridCommandEventArgs e) 
    {
    // Retrieve the new text 
    int nColPositionIndex = 2; // 0-based position of the column
    int nColFromIndex = 3; // 0-based position of the column TextBox txtPosition = (TextBox) e.Item.Cells[nColPositionIndex].Controls[0];
            TextBox txtFrom = (TextBox) e.Item.Cells[nColFromIndex].Controls[0]; // Retrieve the new text in the templated column
    TextBox txtFirstName = (TextBox) e.Item.FindControl("txtFirstName");
    TextBox txtLastName = (TextBox) e.Item.FindControl("txtLastName");
    DropDownList ddTitles = (DropDownList) e.Item.FindControl("ddTitles"); // Prepare the command text
    StringBuilder sb = new StringBuilder("");
    sb.Append("UPDATE Employees SET ");
    sb.Append("title=@sPosition, country=@sCountry, titleofcourtesy=@sTitle, ");
    sb.Append("firstname=@sFirstName, lastname=@sLastName ");
    sb.Append("WHERE employeeid=@nEmpID"); SqlConnection conn = new SqlConnection(txtConn.Text);
    SqlCommand cmd = new SqlCommand(sb.ToString(), conn); SqlParameter p1 = new SqlParameter("@nEmpID", SqlDbType.Int);
    p1.Direction = ParameterDirection.Input;
    p1.Value = grid.DataKeys[e.Item.ItemIndex];
    cmd.Parameters.Add(p1); SqlParameter p2 = new SqlParameter("@sPosition", SqlDbType.NVarChar, 30);
    p2.Direction = ParameterDirection.Input;
    p2.Value = txtPosition.Text;
    cmd.Parameters.Add(p2); SqlParameter p3 = new SqlParameter("@sCountry", SqlDbType.NVarChar, 15);
    p3.Direction = ParameterDirection.Input;
    p3.Value = txtFrom.Text;
    cmd.Parameters.Add(p3); // Retrieve the new text in the templated column SqlParameter p4 = new SqlParameter("@sTitle", SqlDbType.NVarChar, 25);
    p4.Direction = ParameterDirection.Input;
    p4.Value = ddTitles.SelectedItem.Text;
    cmd.Parameters.Add(p4); SqlParameter p5 = new SqlParameter("@sFirstName", SqlDbType.NVarChar, 10);
    p5.Direction = ParameterDirection.Input;
    p5.Value = txtFirstName.Text;
    cmd.Parameters.Add(p5); SqlParameter p6 = new SqlParameter("@sLastName", SqlDbType.NVarChar, 20);
    p6.Direction = ParameterDirection.Input;
    p6.Value = txtLastName.Text;
    cmd.Parameters.Add(p6);
    conn.Open();
    cmd.ExecuteNonQuery();
    conn.Close();
    // Reset the edit mode for the current item
    grid.EditItemIndex = -1; // Refresh the grid
    UpdateView();
    } public void CancelCommand(Object sender, DataGridCommandEventArgs e) 
    {
    // Reset the edit mode for the current item
    grid.EditItemIndex = -1; // Refresh the grid
    UpdateView();
    } private void UpdateView()
    {
    SqlConnection conn = new SqlConnection(txtConn.Text);
    SqlDataAdapter da = new SqlDataAdapter(txtCommand.Text, conn);

    DataSet ds = new DataSet();
    da.Fill(ds, "MyTable"); // Bind the data
    grid.DataSource = ds.Tables["MyTable"]; // Display the data
    grid.DataBind();
    }</script>
    <body bgcolor="ivory" style="font-family:arial;font-size:small"><!-- ASP.NET topbar -->
    <h2>Template Editing with Update</h2>
    <asp:Label runat="server" cssclass="StdText" font-bold="true">Current path: </asp:label>
    <asp:Label runat="server" id="lblURL" cssclass="StdText" style="color:blue"></asp:label><form runat="server">  <table>
      <tr>
      <td><asp:label runat="server"  text="Connection String" cssclass="StdText" /></td>
      <td><asp:textbox runat="server" id="txtConn"
    Enabled="false"
      cssclass="StdTextBox"
    width="600px"
    text="DATABASE=Northwind;SERVER='192.168.1.144';UID=sa;PWD=sa;" /></td></tr>      <tr>
      <td><asp:label runat="server"  text="Command Text" cssclass="StdText"/></td>
      <td><asp:textbox runat="server" id="txtCommand" 
            Enabled="false"
    width="600px"
      cssclass="StdTextBox"
    text="SELECT employeeid, titleofcourtesy, firstname, lastname, title, country FROM Employees" /></td></tr></table>        <br><br>
        <asp:linkbutton runat="server" text="Go get data..." onclick="OnLoadData" />    <hr>    <asp:DataGrid id="grid" runat="server"  
    AutoGenerateColumns="false"
    CssClass="Shadow" BackColor="white"
    CellPadding="2" CellSpacing="0" 
    BorderStyle="solid" BorderColor="black" BorderWidth="1"
    font-size="x-small" font-names="verdana"
    DataKeyField="employeeid"
    OnItemCreated="ItemCreated"
            OnEditCommand="EditCommand"
            OnUpdateCommand="UpdateCommand"
            OnCancelCommand="CancelCommand"> <AlternatingItemStyle BackColor="palegoldenrod" />
    <ItemStyle BackColor="beige" />
    <EditItemStyle BackColor="yellow" Font-Bold="true" />
    <HeaderStyle ForeColor="white" BackColor="brown" HorizontalAlign="center" Font-Bold="true" />        <columns>
       <asp:BoundColumn runat="server" DataField="employeeid" HeaderText="ID" Readonly="true"
    DataFormatString="<span style='margin-left:5;margin-right:5'>{0}</span>" >
    <itemstyle backcolor="lightblue" font-bold="true" HorizontalAlign="right" />
       </asp:BoundColumn>    <asp:TemplateColumn runat="server" HeaderText="Employee Name">
    <itemtemplate>
    <asp:label runat="server" 
    style="margin-left:5;margin-right:5"
    Text='<%# DataBinder.Eval(Container.DataItem, "TitleOfCourtesy") + "<b> " + 
      DataBinder.Eval(Container.DataItem, "LastName") + "</b>" + ", " + 
      DataBinder.Eval(Container.DataItem, "FirstName") %>' />
    </itemtemplate>
    <edititemtemplate>
    <asp:dropdownlist runat="server" id="ddTitles" 
    DataSource='<% # aTitleOfCourtesy %>' />
    <asp:textbox runat="server" width="80px" id="txtFirstName"
    Text='<%# DataBinder.Eval(Container.DataItem, "firstname") %>' /><br>
    <asp:textbox runat="server" width="140px" id="txtLastName"
    Text='<%# DataBinder.Eval(Container.DataItem, "lastname") %>' />
    </edititemtemplate>
       </asp:TemplateColumn>    <asp:BoundColumn runat="server" DataField="title" HeaderText="Position" />
       <asp:BoundColumn runat="server" DataField="country" HeaderText="From" />    <asp:EditCommandColumn runat="server"                  
    EditText="<img src=edit.gif border=0 align=absmiddle alt='Edit this item'>"
    UpdateText="<img src=ok.gif border=0 align=absmiddle alt='Save changes'>"
    CancelText="<img src=cancel.gif border=0 align=absmiddle alt='Cancel editing'>">
    <itemstyle BackColor="yellow" HorizontalAlign="center" />
       </asp:EditCommandColumn>  </columns>
         </asp:DataGrid>     <hr>
         <asp:label runat="server" id="lblCurrent" />
    </form></body>
    </html>