2010-03-12 4 views
0

У меня есть контроль DataListDataList режим редактирования

<asp:DataList ID="DataList1" runat="server" DataKeyField="AdmissionNo" OnCancelCommand="DataList1_CancelCommand1" 
      OnEditCommand="DataList1_EditCommand1" OnUpdateCommand="DataList1_UpdateCommand1" 
      Width="300px"> 

      <ItemTemplate> 
       <tr> 
        <td height="31px"> 
         <asp:Label ID="lblStudentName" runat="server" Text="StudentName :" Font-Bold="true"></asp:Label> 
         <%# DataBinder.Eval(Container.DataItem, "StudentName") %> 
        </td> 
        <td height="31px"> 
         <asp:LinkButton ID="lnkEdit" runat="server" CommandName="edit">Edit</asp:LinkButton> 
        </td> 
       </tr> 
       <tr> 
        <td> 
         <asp:Label ID="lblAdmissionNo" runat="server" Text="AdmissionNo :" Font-Bold="true"></asp:Label> 
         <%# DataBinder.Eval(Container.DataItem, "AdmissionNo")%> 
        </td> 
       </tr> 

       <tr> 
        <td height="31px"> 
         <asp:Label ID="lblStudentRollNo" runat="server" Text="StdentRollNo :" Font-Bold="true"></asp:Label> 
         <%# DataBinder.Eval(Container.DataItem, "StdentRollNo") %> 
        </td> 
        <td height="31px"> 
         <asp:LinkButton ID="lnkEditroll" runat="server" CommandName="edit">Edit</asp:LinkButton> 
        </td> 
       </tr> 
     </ItemTemplate> 
      <EditItemTemplate> 
       <tr> 
        <td height="31px"> 
         <asp:Label ID="lblStudentName" runat="server" Text="StudentName :" Font-Bold="true"></asp:Label> 
         <asp:TextBox ID="txtProductName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "StudentName") %>'></asp:TextBox> 
        </td> 
        <td> 
         <asp:LinkButton ID="lnkUpdate" runat="server" CommandName="update">Update</asp:LinkButton> 
         <asp:LinkButton ID="lnkCancel" runat="server" CommandName="cancel">Cancel</asp:LinkButton> 
        </td> 
       </tr> 
       <tr> 
        <td height="31px"> 
         <asp:Label ID="lblAdmissionNo" runat="server" Text="AdmissionNo :" Font-Bold="true"></asp:Label> 
         <%# DataBinder.Eval(Container.DataItem, "AdmissionNo")%> 
        </td> 
       </tr> 

       <tr> 
        <td height="31px"> 
         <asp:Label ID="lblStudentRollNo" runat="server" Text="StudentRollNo :" Font-Bold="true"></asp:Label> 
         <asp:TextBox ID="txtStudentRollNo" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "StdentRollNo") %>'></asp:TextBox> 
        </td> 
        <td> 
         <asp:LinkButton ID="LinkButton1" runat="server" CommandName="update">Update</asp:LinkButton> 
         <asp:LinkButton ID="LinkButton2" runat="server" CommandName="cancel">Cancel</asp:LinkButton> 
        </td> 
       </tr> 
      </EditItemTemplate> 
      <FooterTemplate> 
       </table> 
      </FooterTemplate> 
     </asp:DataList> 

код позади:

protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!Page.IsPostBack) 
     { 
      DataTable dt = new DataTable(); 
      dt = obj.GetSamples(); 

      DataList1.DataSource = dt; 
      DataList1.DataBind(); 
     } 

    } 


    public void DataBind() 
    { 
     DataTable dt = new DataTable(); 
     dt = obj.GetSamples(); 

     DataList1.DataSource = dt; 
     DataList1.DataBind(); 
    } 

    protected void DataList1_EditCommand1(object source, DataListCommandEventArgs e) 
    { 

     DataList1.EditItemIndex = e.Item.ItemIndex; 

     DataBind(); 


    } 

    protected void DataList1_CancelCommand1(object source, DataListCommandEventArgs e) 
    { 

     DataList1.EditItemIndex = -1; 
     DataBind(); 

    } 



    protected void DataList1_UpdateCommand1(object source, DataListCommandEventArgs e) 
    { // Get the DataKey value associated with current Item Index. 
     // int AdmissionNo = Convert.ToInt32(DataList1.DataKeys[e.Item.ItemIndex]); 
     string AdmissionNo = DataList1.DataKeys[e.Item.ItemIndex].ToString(); 

     // Get updated value entered by user in textbox control for 
     // ProductName field. 
     TextBox txtProductName; 
     txtProductName = (TextBox)e.Item.FindControl("txtProductName"); 

     TextBox txtStudentRollNo; 
     txtStudentRollNo = (TextBox)e.Item.FindControl("txtStudentRollNo"); 

     // string variable to store the connection string 
     // retrieved from the connectionStrings section of web.config 
     string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString; 

     // sql connection object 
     SqlConnection mySqlConnection = new SqlConnection(connectionString); 

     // sql command object initialized with update command text 
     SqlCommand mySqlCommand = new SqlCommand("update SchoolAdmissionForm set [email protected] ,[email protected] where [email protected]", mySqlConnection); 
     mySqlCommand.Parameters.Add("@studentname", SqlDbType.VarChar).Value = txtProductName.Text; 
     mySqlCommand.Parameters.Add("@admissionno", SqlDbType.VarChar).Value = AdmissionNo; 
     mySqlCommand.Parameters.Add("@studentroll", SqlDbType.VarChar).Value = txtStudentRollNo.Text; 


     // check the connection state and open it accordingly. 
     if (mySqlConnection.State == ConnectionState.Closed) 
      mySqlConnection.Open(); 

     // execute sql update query 
     mySqlCommand.ExecuteNonQuery(); 

     // check the connection state and close it accordingly. 
     if (mySqlConnection.State == ConnectionState.Open) 
      mySqlConnection.Close(); 

     // reset the DataList mode back to its initial state 
     DataList1.EditItemIndex = -1; 
     DataBind(); 
     // BindDataList(); 

    } 

Но она отлично работает .... но когда я нажимаю редактировать команду как поля

1 .StudentName

2.StudentRollNo

Я получаю текстовые поля ко всем полям, где я помещал текстовое поле, когда я нажимаю команду «редактировать», а не отдельное поле. но я должен получить только текстовое поле, видимое для поля, на которое я нажимаю «редактировать», а остальные остаются такими же, не отображая текстовые поля, даже если они находятся в editmode.

ответ

0

Если вы устанавливаете DataList1.EditItemIndex, это относится ко всему изделию. Шаблон элемента заменяется шаблоном редактирования. Это делается не на основе контроля, а на основе шаблона всего шаблона.

В вашем EditTemplate есть несколько текстовых полей, поэтому строка, находящаяся в режиме редактирования, будет отображать весь этот шаблон, а не только один элемент управления в шаблоне. Обратите внимание, что вы устанавливаете весь индекс редактирования DataList и не устанавливаете управление X в пределах DataList.

Если вы хотите контролировать определенный уровень редактирования шаблонов, вам нужно будет сделать это вручную, поскольку элемент управления DataList предназначен для редактирования целых строк данных.

Смежные вопросы