2017-02-21 37 views
0

我有2個表,我想從中獲取數據。第一個表格是承包商個人信息的承包商表格,第二個表格是公司表格,其中有兩列,CompanyName和CompanyID。兩個表具有相同的列,CompanyID。如何獲取SelectedIndexChanged以獲取公司名稱而不是companyid到文本框,2個不同的表中?

當前代碼我有一個帶有「選擇」列的GridView,SelectedIndexChanged返回數據庫中的值以填充文本框。

我想要做的是獲取公司的名稱,而不是公司名稱填入文本框(txtCompany),我該如何修改我下面的當前代碼這樣做?

ASPX

<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox> 
<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox> 
<asp:TextBox ID="txtPID" runat="server"></asp:TextBox> 
<asp:TextBox ID="txtCompany" runat="server"></asp:TextBox> 

<asp:GridView ID="TDetails" DataSourceID="SqlDataSource1" DataKeyNames="PersonID" AutoGenerateColumns="false" runat="server" OnSelectedIndexChanged="TDetails_SelectedIndexChanged" > 
     <HeaderStyle BackColor="gray" ForeColor="White" /> 
     <Columns 
      <asp:TemplateField> 
       <ItemTemplate> 
        <asp:LinkButton ID="lbtnSelect" runat="server" CommandName="Select" Text="Select" /> 
       </ItemTemplate> 
      </asp:TemplateField> 
      <asp:TemplateField HeaderText="Last Name"> 
       <ItemTemplate> 
        <asp:Label ID="lblLastName" runat="server" Text='<%#Eval("LastName") %>' /> 
       </ItemTemplate> 
      </asp:TemplateField> 
      <asp:TemplateField HeaderText="First Name"> 
       <ItemTemplate> 
        <asp:Label ID="lblFirstName" runat="server" Text='<%#Eval("FirstName") %>' /> 
       </ItemTemplate> 
      </asp:TemplateField> 
      <asp:TemplateField HeaderText="Company" Visible="false"> 
       <ItemTemplate> 
        <asp:Label ID="lblCompany" runat="server" Text='<%#Eval("CompanyID") %>' /> 
       </ItemTemplate> 
      </asp:TemplateField> 
      <asp:TemplateField HeaderText="PersonID" Visible="false"> 
       <ItemTemplate> 
        <asp:Label ID="lblPID" runat="server" Text='<%#Eval("PersonID") %>' /> 
       </ItemTemplate> 
      </asp:TemplateField> 
     </Columns> 
    </asp:GridView> 

.CS

protected void TDetails_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     txtPID.Text = TDetails.DataKeys[TwicDetails.SelectedRow.RowIndex].Value.ToString(); 
     txtLastName.Text = (TDetails.SelectedRow.FindControl("lblLastName") as Label).Text; 
     txtFirstName.Text = (TDetails.SelectedRow.FindControl("lblFirstName") as Label).Text; 
     txtCompany.Text = (TDetails.SelectedRow.FindControl("lblCompany") as Label).Text; 
     } 

回答

1

您可以修改您的SQL查詢來獲取CompanyName以及像你是如何獲取的CompanyId並將其綁定到GridView和設置能見度false,最後你可以像設置其他控件一樣設置文本框的值: -

SQL查詢: -

SELECT CompanyId, CompanyName, .... 
FROM tblCompany.. 

.aspx的: -

<asp:TemplateField HeaderText="Company" Visible="false"> 
    <ItemTemplate> 
     <asp:Label ID="lblCompanyName" runat="server" Text='<%#Eval("CompanyName") %>' /> 
    </ItemTemplate> 
</asp:TemplateField>