2017-02-24 4 views
0

라디오 버튼 목록 템플릿 열 및 extbox 밑줄이있는 GridView가 있습니다. 이 튜토리얼을 선택하여 사용하면 라디오 버튼이 즉시 업데이트되어 원하는 기능을 실현할 수 있습니다. http://www.dotnetcurry.com/ShowArticle.aspx?ID=261. 그것은 위대한 작품.텍스트 상자에 데이터베이스가 성공적으로 새 값으로 업데이트되는 동안 포스트 백 이후에 값이 표시됩니다.

바닥 글의 새 값이 변경되면 SqlDataSource Update()를 통해 TextChanged() 이벤트에서 SQL이 성공적으로 업데이트되지만 포스트 백 이후에는 이전 값이 텍스트 상자에 반환됩니다. 수표로, 나는 페이지에있는 라벨에 새로운 가치를 전달하고 올바르게 표시됩니다.

If (! IsPostBack)의 Page_Load()에 GridView1.DataBind()를 넣으려고했으나 변경되었거나 sqldatasource가 업데이트되지 않은 경우 radiobuttonlist 항목이 선택 상태를 유지하지 못하게합니다.

이 앱이 프로토 타입이기 때문에 나는 사용자가 텍스트 상자에 MYID를 입력하고 버튼을 클릭 할 때 페이지로드 후 특정 레코드를로드하는 중입니다. 결국 그리드는 다른 페이지에서 오는 QueryString을 통해 제공된 값으로로드됩니다.

본질적으로 나는 radiobuttonlist처럼 작동하도록 텍스트 상자를 원합니다. 값을 변경하자마자 데이터베이스를 업데이트하고 포스트 백 이후에 grid/textbx에 새 값을 표시하려고합니다. 내가 누락 된 명백한 것이 있습니까?

UPDDATE : 추가 radiobuttonlist의 SelectedIndexChanged 이벤트 코드 UPDATE 2 :은 SqlDataSource와 UPDATE 3을 추가 : 솔루션, 사용자 정의 방법을 통해 직접 SQL 데이터베이스를 업데이트하는 것이 었의 SqlDataSource에서 2 업데이트 쿼리를 제거했습니다. TextChanged 이벤트 코드가 업데이트되고 사용자 정의 메서드가 추가되었습니다.

HTML :

<asp:GridView ID="GridView1" runat="server" 
     AutoGenerateColumns="False" 
     DataKeyNames="MYID" 
     DataSourceID="SqlDataSource1" 
     onrowdatabound="GridView1_RowDataBound" 
     ShowFooter="True" > 
     <Columns> 
<asp:BoundField DataField="MYID" HeaderText="MYID" ReadOnly="True" 
       SortExpression="MYID" /> 
      <asp:BoundField DataField="DocID" HeaderText="DocID" ReadOnly="True" 
       SortExpression="DocID" /> 
      <asp:BoundField DataField="ItemID" HeaderText="ItemID" 
       InsertVisible="False" ReadOnly="True" SortExpression="ItemID" /> 
      <asp:TemplateField HeaderText="Item" SortExpression="Item"> 
       <ItemTemplate> 
        <asp:Label ID="Label1" runat="server" Text='<%# Bind("Item") %>'></asp:Label> 
       </ItemTemplate> 
       <FooterTemplate > 
       <asp:TextBox ID="txtComment1" runat="server" 
        Text='Section 1 Comments' AutoPostBack="True" 
        ontextchanged="txtComment1_TextChanged" MaxLength="1000" 
        TextMode="MultiLine" Width="650px"></asp:TextBox> 
      </FooterTemplate> 
      </asp:TemplateField> 
       <asp:TemplateField HeaderText=" -- 1 -- 2 -- 3 -- 4 -- 5 -- " >  
        <ItemTemplate> 
       <asp:RadioButtonList AutoPostBack="True" ID="rblRating" runat="server" 
        Enabled="true" SelectedIndex='<%#Convert.ToInt32(DataBinder.Eval(Container.DataItem , "Rating"))%>' 
        OnSelectedIndexChanged="rblRating_SelectedIndexChanged" RepeatDirection="Horizontal"> 
        <asp:ListItem Value="0">0</asp:ListItem> 
        <asp:ListItem Value="1">1</asp:ListItem> 
        <asp:ListItem Value="2">2</asp:ListItem> 
        <asp:ListItem Value="3">3</asp:ListItem> 
        <asp:ListItem Value="4">4</asp:ListItem> 
        <asp:ListItem Value="5">5</asp:ListItem>       
       </asp:RadioButtonList> 
      </ItemTemplate> 

     </asp:TemplateField> 
      <asp:BoundField DataField="Rating" HeaderText="Rating" 
       SortExpression="Rating" ReadOnly="True" /> 
     </Columns> 
    </asp:GridView> 
     <asp:Label ID="lblComments1" runat="server" Text="Label"></asp:Label> 
    </div> 

.CS :

protected void UpdateComment1(int myid, string comment) 
     {             
      using (SqlConnection con = new SqlConnection(conStr))) 
     { 
     string cmdStr = "UPDATE tblComments SET Comment1 = @Comment1 WHERE MYID = @MYID"; 

       using (SqlCommand cmd = new SqlCommand(cmdStr, con))) 
       { 
       cmd.Parameters.AddWithValue("@MYID", myid); 
       cmd.Parameters.AddWithValue("@Comment1", comment); 
       try 
       { 
        con.Open(); 
        int affectedRows = cmd.ExecuteNonQuery(); 
       } 
       catch (SqlException ex) 
       { 
        Response.Write(ex.Message); 
       } 
     } 
     } 
     } 
protected void txtComment1_TextChanged(object sender, EventArgs e) 
     { 
      TextBox tbox = (TextBox)sender; 
      string oldComment1 = ViewState["OldComment1"].ToString(); //value saved from PreRender() 
      string newComment1 = (GridView1.FooterRow.FindControl("txtComment1") as TextBox).Text; 
      ViewState["Section1Comments"] = newComment1; 

       if(oldComment1 != newComment1) 
       { 
        //<<TODO>>update history table 
       } 

      if (newComment1 != null) 
      { 
      //update SQL directly via custom method     
       UpdateComment1(Convert.ToInt32(MYID), newComment1); 
      } 
      GridView1.DataBind(); 
     } 

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
     { 
      DataRowView drv = e.Row.DataItem as DataRowView; 
      RadioButtonList rbtnl = (RadioButtonList)e.Row.FindControl("rblRating"); 

      if (e.Row.RowType == DataControlRowType.DataRow) 
      { 
       if ((e.Row.RowState & DataControlRowState.Normal) > 0) //.Edit, .Normal, .Alternate, .Selected 
       { 
      //check for null 
        if (rbtnl.SelectedItem != null) 
        { 
         if (rbtnl.SelectedItem.Text == "0") //if rating isn’t inserted into SQL yet, deselect all 5 radio buttons 
         { 
          rbtnl.SelectedItem.Selected = false; 
         } 
          rbtnl.SelectedValue = drv[4].ToString(); 
        } 
       } 

       //remove extra list item 
       ListItem blank = rbtnl.Items.FindByValue("0"); 
       if (blank != null) 
       { 
        rbtnl.Items.Remove(blank);//always remove list item at index zero 
       } 
      } 
     } 

protected void rblRating_SelectedIndexChanged(object sender, EventArgs e) 
     { 
      string rate = string.Empty; 

      RadioButtonList rBtnList = (RadioButtonList)sender; 
      GridViewRow gvr = (GridViewRow)rBtnList.Parent.Parent; 

      if (rBtnList.SelectedValue != null) 
      { 
       rate = rBtnList.SelectedValue; 

       SqlDataSource1.UpdateParameters["Rating"].DefaultValue = rate; 
       SqlDataSource1.UpdateParameters["MYID"].DefaultValue = gvr.Cells[0].Text; 
       SqlDataSource1.UpdateParameters["ItemID"].DefaultValue = gvr.Cells[2].Text; 
      } 
      else 
      {  
      } 
      SqlDataSource1.Update(); 
      GridView1.DataBind(); 
     } 

SQL &의 SqlDataSource :

<asp:SqlDataSource 
    ID="SqlDataSource1" 
    runat="server" 
    ConnectionString="<%$ ConnectionStrings:SomeConnectionString %>" 
    SelectCommand="SelectSection1" 
    UpdateCommand="UPDATE tblDetails SET Rating = @Rating WHERE MYID = @myid AND ItemID = @ItemID; 
    --UPDATE [tblComments] SET [Comment1] = @Comment1 WHERE MYID [email protected]; " 
    SelectCommandType="StoredProcedure" > 
     <SelectParameters> 
      <asp:ControlParameter ControlID="TextBox1" DefaultValue="0"    Name="eprid" PropertyName="Text" Type="Int32" /> 
     </SelectParameters> 
     <UpdateParameters> 
      <asp:Parameter Name="Rating" Type="Int32" /> 
      <asp:Parameter Name="myid" Type="Int32" /> 
      <asp:Parameter Name="ItemID" Type="Int32" /> 
      <asp:Parameter Name="Comment1" Type="String" /> 
      </UpdateParameters> 
</asp:SqlDataSource> 

ALTER PROCEDURE [dbo].[SelectSection1] 
    @myid int 
AS 
BEGIN 
    -- SET NOCOUNT ON added to prevent extra result sets from 
    -- interfering with SELECT statements. 
    SET NOCOUNT ON; 

--Has Form been submitted to tblComments yet? 
declare @docid int 
set @docid =(select distinct d.docid  
    from dbo.tblEmployee e 
    full outer join dbo.tblDetails d on e.MYID = d.myid 
    where e.myid = @myid) 

IF @docid is null 

----if not submitted yet, fill grid with evaluation items only, set rating to NULL 
BEGIN 
SELECT 
     @myid As MYID 
     ,0 as DocID 
     ,ItemID 
     ,Item 
     ,0 as Rating 
     ,'' As Comment1 

    FROM [EPR].[dbo].[tblItems] 

    where SectionID = 1 and Active = 1 


    END 
-- if submitted (DocID exists), fill grid with evaluations items and rating 
ELSE 
    BEGIN 
    SELECT 
     d.eprid 
     ,d.DocID 
     ,i.[ItemID] 
     ,i.[Item] 
     ,d.Rating 
     ,c.Comment1 

    FROM [EPR].[dbo].[tblItems] i 

    join tblDetails d on i.ItemID = d.ItemID 
    join tblComments c on d.MYID = c.MYID 

    --Competence Section 
    where i.SectionID = 1 and i.Active = 1 and d.MYID = @myid 

    END 
END 

답변

0

내 솔루션은 내 업데이트 된 질문에 포함되어 있습니다. 내 오류 sqldatasource 2 업데이트 쿼리를 배치 할 것으로 보인다. 하나의 업데이트 쿼리를 제거하고 textchanged 이벤트에서 즉시 업데이트 할 텍스트 상자를 가져오고 selectedindexchanged를 즉시 업데이트 할 radiobuttonlist를 얻기 위해 SQL 데이터베이스를 직접 업데이트하는 사용자 지정 메서드를 만들었습니다. 세미콜론으로 각 쿼리를 분리하면 sqldatasource를 사용하여 2 개의 UPDATE 쿼리를 가질 수 있지만 내 경우에는 작동하지 않는다는 것을 읽었습니다.

0

데이터베이스를 업데이트하고 즉시 업데이트 된 값을 가져 오려고하지만 SQL 작업이 끝날 때까지 C# 코드가 대기하지 않습니다. 이 읽어 보시기 바랍니다 :

How to requery updated values immediately after update procedure runs

난 당신이 별도로 변경된 텍스트 상자의 코드를 업데이트하는 것이 좋습니다.

//after all things done: 
theTextbox.Text = the_value_that_it_sended. 
+0

@Farzin Kanzi에게 올바른 방향으로 나를 가르쳐 주신 것에 대해 감사드립니다.나는 주말에 LINQ를 읽었습니다. 전에 그것을 사용할 필요가 없었습니다. 왜 radiobuttonlist에 대한 업데이트가 postback시 UI/gridview에서 즉시 나타나지만 두 이벤트에 대한 코드가 거의 동일 할 때 textbox에서 나타나지 않는지 말해 줄 수 있습니까? radiobuttonlist selectedindexchanged 이벤트 코드를 포함하도록 질문을 업데이트했습니다. – Doreen

+0

이제 내 대답에 의심 스럽습니다! 제발이게 뭐지 :'텍스트 = '섹션 1 의견'텍스트 상자에? –

+0

재밌 네가 물어봐야 겠어. 그냥 아침에 텍스트 속성을 Text = '<% # Bind ("Comment1") %>'로 바꿨다. 그러나 page_Load에서도 텍스트 상자에 데이터베이스 값이 채워지지 않았다. 나는 문제가 SQL 쿼리와 같다고 생각한다. 표를 채우기위한 select 문은 2 개의 표를 조인 한 것이고 별도의 열이있는 경우 쿼리 결과는 표의 모든 항목에 의해 주석 필드를 표시합니다. 나는 그것이 단지 한 번 나타나기를 바란다. 왜냐하면 내가 그것을 꼬리말에 넣는 이유 다. 그러나 나는 그것이 오작동하는 이유 일 수 있다고 생각한다. 내가 텍스트 상자에 대해서만 별도의 sqldatasource가 필요한지 궁금하다. – Doreen

관련 문제