【问题标题】:How can I fetch values from a same column into different textbox?如何将同一列中的值提取到不同的文本框中?
【发布时间】:2019-06-27 21:59:12
【问题描述】:

我在将动态数据显示到文本框中时遇到了困难。我的情况是,我有多个文本框,我想从列名为“registration_charges”和“amount”的表中获取值。现在,registration_charges 列包含数据,例如 'OPD_CHARGES'、'DR.Charges' 和 'amount' 列包含数据,例如:- 5000、1000。我想在文本框中相应地显示金额。

<asp:Label runat="server" >OPD Ch.</asp:Label>
<asp:TextBox ID="txtopd_charges" runat="server" Width="100px"  
style="text- 
align: right;float:right;margin-right:15px;">/-</asp:TextBox>
<asp:Label runat="server" >DR Ch.</asp:Label>
<asp:TextBox ID="txtdr_charges" runat="server" Width="100px"  
style="text- 
align: right;float:right;margin-right:15px;">/-</asp:TextBox>

后端代码:

//connection code
con.Open();
SqlCommand cmd = new SqlCommand("SELECT amount FROM 
Mst_Charges WHERE registration_charges IN('OPD_CHARGES', 
DR.Charges')",  con);

SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
   txtopd_charges.Text = ???
   txtdr_charges.Text =  ???         

}
else
{

}
}
catch (Exception ex)
{
}
}    

【问题讨论】:

  • 为什么实际代码不起作用?您是否在查询编辑器中尝试过查询?

标签: c# asp.net sql-server webforms


【解决方案1】:

在您的查询中,您必须选择 registration_charges 以及 amount

SqlCommand cmd = new SqlCommand("SELECT amount,registration_charges  FROM 
   Mst_Charges WHERE registration_charges IN('OPD_CHARGES', 
   DR.Charges')",  con);

您可以像这样获取 DataTable 的数据:

txtopd_charges.Text = dt.Rows[0]["amount"].ToString();
txtdr_charges.Text =  dt.Rows[0]["registration_charges"].ToString();

更新 您可以使用Repeater 绑定数据并在ItemTemplate 内初始化您的文本框,这将重复您的数据存在于DataTable 中。

Aspx 代码

<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
    <ItemTemplate>
        <asp:TextBox ID="txtopd_charges" Text='<%# Eval("amount") %>' runat="server"></asp:TextBox>
        <asp:TextBox ID="txtdr_charges" Text='<%# Eval("registration_charges") %>' runat="server"></asp:TextBox>
    </ItemTemplate>
</asp:Repeater>

在你的 C#

if (dt.Rows.Count > 0)
{
   Repeater1.DataSource = dt;
   Repeater1.DataBind();
}

【讨论】:

  • 我想要这样的输出 txtopd_charges.Text = 5000 txtdr_charges.Text=1000 即从单列我试图获取多个值
  • 您想显示该值的总和,还是想单独显示它们?显示来自 SQL Query 的响应的任何示例数据,这将有助于找出解决方案。
  • 您可以在您的Webform中添加Repeater并将其与DataTable绑定,然后您可以在您的TextBox中访问这些数据。
猜你喜欢
  • 2015-07-28
  • 2018-11-13
  • 2021-12-21
  • 2023-03-28
  • 2021-03-31
  • 2015-06-03
  • 2017-09-09
  • 1970-01-01
相关资源
最近更新 更多