我将尝试通过传递C#变量来动态更改网页上5个HTML按钮的文本/值。我通过页面加载中的SQL查询生成变量,但无法想出如何将变量传递给按钮。
DataSet ds= new DataSet();
DataTable dt= new DataTable();
connection.Open();
string commandstring = "SELECT TOP (5) [ButtonVal] FROM Table";
SqlDataAdapter adptr = new SqlDataAdapter(commandstring, connection);
adptr.Fill(ds);
dt = ds.Tables[0];
Btn1 = System.Convert.ToString(dt.Rows[0][0]);
Btn2 = System.Convert.ToString(dt.Rows[1][0]);
Btn3 = System.Convert.ToString(dt.Rows[2][0]);
Btn4 = System.Convert.ToString(dt.Rows[3][0]);
Btn5 = System.Convert.ToString(dt.Rows[4][0]);
HTML:
<table>
<tr>
<td><asp:Button ID="Button1" text="XXX" value ="XXX" style="font-size:8px;height:30px;width:60px" runat="server" AutoPostBack="true" OnClick="ChangeRedirect_Click" /> </td>
<td><asp:Button ID="Button2" text="XXX" value ="XXX" style="font-size:8px;height:30px;width:60px" runat="server" AutoPostBack="true" OnClick="ChangeRedirect_Click" /> </td>
<td><asp:Button ID="Button3" text="XXX" value ="XXX" style="font-size:8px;height:30px;width:60px" runat="server" AutoPostBack="true" OnClick="ChangeRedirect_Click" /> </td>
<td><asp:Button ID="Button4" text="XXX" value ="XXX" style="font-size:8px;height:30px;width:60px" runat="server" AutoPostBack="true" OnClick="ChangeRedirect_Click" /> </td>
<td><asp:Button ID="Button5" text="XXX" value ="XXX" style="font-size:8px;height:30px;width:60px" runat="server" AutoPostBack="true" OnClick="ChangeRedirect_Click" /> </td>
<tr />
OnClick函数根据按钮的值重定向到另一个页面。
* 根据Jim W的答案编辑 *
1)
C#:
public string Btn1
if (!Page.IsPostBack)
{
Btn1 = (dt.Rows[0][0]).ToString();
}
HTML:
<td><asp:Button ID="Button1" Text="<%# Btn1 %>" Value ="<%# Btn1 %>"
style="font-size:8px;height:30px;width:60px" runat="server"
AutoPostBack="true" OnClick="ChangeRedirect_Click" /> </td>
Output:
Blank Button
2)
C#:
if (!Page.IsPostBack)
{
Button1.Text = (dt.Rows[0][0]).ToString();
}
HTML:
<td><asp:Button ID="Button1" Text="<%# Button1 %>" Value ="<%# Button1 %>"
style="font-size:8px;height:30px;width:60px" runat="server"
AutoPostBack="true" OnClick="ChangeRedirect_Click" /> </td>
Output:
Button text is "System.Web.UI.WebControls.Button"
3)
C#:
public string Btn1
if (!Page.IsPostBack)
{
Btn1 = System.Convert.ToString(dt.Rows[0][0]);
}
HTML:
<td><asp:Button ID="Button1" Text="<%# Btn1 %>" Value ="<%# Btn1 %>"
style="font-size:8px;height:30px;width:60px" runat="server"
AutoPostBack="true" OnClick="ChangeRedirect_Click" /> </td>
Output:
Blank Button
4)
C#:
public string Btn1
if (!Page.IsPostBack)
{
Btn1 = (dt.Rows[0][0]).ToString();
}
HTML:
<td><asp:Button ID="Button1" Text="<%# Btn1 %>" Value ="<%# Btn1 %>"
style="font-size:8px;height:30px;width:60px" runat="server"
AutoPostBack="true" OnClick="ChangeRedirect_Click" /> </td>
Output:
Blank Button
Text=
而不是text=
。 - Jim W says reinstate Monica