如何将数据库值绑定到文本框 [英] how to bind database value to text box

查看:100
本文介绍了如何将数据库值绑定到文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当dropdownlist选择索引已更改时,我从数据库中带来一个值,并且该值要绑定到文本框,我的代码是(在此代码中是绑定列表的值(ddlmonthlypay)如何将该值绑定到文本框)

when dropdownlist selected index changed am bringing a value from database and that value i wants to bind to a text box my code is(in this code am binding value to dropdownlist(ddlmonthlypay) how to bind that value to text box)

protected void ddlNoOfMonths_SelectedIndexChanged(object sender, EventArgs e)
    {
        ddlmonthlypay.Items.Clear();
        ddlmonthlypay.AppendDataBoundItems = true;
        String strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
        String strQuery = "select ID, MonthlyPay from Tmonthlypay where NoOfMonthsID=@NoOfMonthsID";
        SqlConnection con = new SqlConnection(strConnString);
        SqlCommand cmd = new SqlCommand();

        cmd.Parameters.AddWithValue("@NoOfMonthsID", ddlNoOfMonths.SelectedItem.Value);
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = strQuery;
        cmd.Connection = con;
        try
        {
            con.Open();
            ddlmonthlypay.DataSource = cmd.ExecuteReader();
            ddlmonthlypay.DataTextField = "MonthlyPay";
            ddlmonthlypay.DataValueField = "ID";
            ddlmonthlypay.DataBind();
            if (ddlmonthlypay.Items.Count > 1)
            {
                ddlmonthlypay.Enabled = true;
            }
            else
            {
                ddlmonthlypay.Enabled = false;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
            con.Dispose();
        }
           }

推荐答案

下拉列表具有文本和基础值的单独属性。文本框没有此类功能。它仅显示设置为Text属性的内容。如果需要,可以使用Tag属性存储有关从数据库中提取的文本的欲望信息。只需设置标签的值。



请注意,文本框不能有多个值,因此您只需设置文本和标签,这样就不会绑定teh对象与下拉列表一样。
Drop down list has separate properties for the text and the underlying value. Text box doesn't have this kind of feature. It only shows what is set to Text property. If you want, you can use Tag property to store desirend information concerning the text you have fetched from the database. Just set the value of the Tag.

Note that text box can't have multiple values so you just set the text and the tag so you don't bind teh object as you do with drop down list.


Hi,

you just put below code into your try...catch box

try
{
con.Opern();
SqlDataReader sqlRed = cmd.ExecuteReader();
while (sqlRed.Read())
{
       //replace your text box name with TextBox1
       TextBox1.Text = Convert.ToString(sqlRed["MonthlyPay"]);
}

......


这篇关于如何将数据库值绑定到文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆