可以从字符串中获取值

时间:2012-10-06 01:10:41

标签: asp.net

所以我试图在点击按钮后显示用户输入信息。我收到消息,但它确实显示输入到文本框中的值。我错过了什么? 这是我的代码

private string _eyecolor;
    public string Eyecolor
    {
        get { return _eyecolor; }
        set
        {
            if (!string.IsNullOrEmpty(value))
            {
                _eyecolor = value.Substring(0, 1).ToUpper() + value.Substring(1);
            }
            else
            {
                _eyecolor = value;
            }
        }
    }

    public string getEyeColor()
    {
        return "You have " + _eyecolor + "eyes!!";
    }

这是我的HTML代码:

     <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Label runat="server" ID="lbl_1" AssociatedControlID="txtb1" Text="what is your eyes color?" Autopostback="true" />
    <asp:TextBox ID="txtb1" runat="server" />
    <asp:Button ID="btn_submit" Text="Submit" runat="server" OnClick="subSubmit" />
    <asp:Label runat="server" ID="lbl_output" />
    </div>
    </form>
</body>
</html>

和我的代码隐藏:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
   Profile P = new Profile();
    protected void Page_Load(object sender, EventArgs e)
    {

    }
protected void  subSubmit(object sender, EventArgs e)
{
   lbl_output.Text=P.getMsg();
   lbl_output.Text+=P.getEyeColor();
}
}

2 个答案:

答案 0 :(得分:1)

您需要一些输入控件,并且您已将其值分配给某些gui控件以显示它。

在html中

<asp:TextBox id="txtInput" runat="server" Text="Blue" ></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<asp:Label id="lbl" runat="server" ></asp:Label>

代码隐藏

protected void Page_Load(object sender, EventArgs e)
{
    Eyecolor = "Blue";
    lbl.Text = getEyeColor();
}


protected void Button1_Click(object sender, EventArgs e)
{
      lbl.Text = txtInput.Text;
}

有问题的更新。

您正在输入用户但未在输出中使用它。 You need to show txtb1 text in lbl_1 Text。这可以通过声明

来完成

lbl.Text = txtInput.Text;

您正在使用Profile类对象,并且您没有为Profile类对象属性if you do not want txtb1 color then you have to assign color to profile object before assigning to lbl_1 text指定颜色,这没有多大意义,但是为了理解您需要类似的东西。

protected void  subSubmit(object sender, EventArgs e)
{
   //lbl_output.Text=P.getMsg();
   P.Eyecolor = "Blue";
   lbl_output.Text+=P.getEyeColor();
}

答案 1 :(得分:0)

正如Adil非常正确地指出的那样,您需要从<asp:TextBox>输入中获取值并将其分配给您的属性Eyecolor

由于getEyeColor是您发布的代码中Profile对象P的函数,因此请尝试将提交处理程序更改为以下内容:

protected void subSubmit(object sender, EventArgs e)
{
    P.Eyecolor = txtb1.Text.Trim; //Add this to set the Eyecolor to user input.
    lbl_output.Text = P.getMsg();
    lbl_output.Text += P.getEyeColor();
}