我正在使用C#asp.net web应用程序。它包含一个网格视图,文本框和一个按钮。我想要的是当我在文本框中输入1然后输入按钮然后自动选择第一行并指向另一行包含所选行的更多详细信息的页面 在我的代码中,可以通过使用鼠标单击超链接重定向到下一页...但这不是我的要求。 这是我的代码
<asp:TextBox ID="txtindex" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Font-Bold="True" Height="39px"
onclick="Button1_Click" Text="go" Width="53px" />
<br />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="acno" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="acno" HeaderText="acno" InsertVisible="False"
ReadOnly="True" SortExpression="acno" />
<asp:HyperLinkField DataNavigateUrlFields="acno" HeaderText="username"
DataNavigateUrlFormatString="~/details.aspx?acno={0}" Target="_blank" DatatextField="username" SortExpression="username" />
<asp:BoundField DataField="rdate" HeaderText="rdate" SortExpression="rdate" />
</Columns>
</asp:GridView>
<br />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:postofficeConnectionString %>"
SelectCommand="SELECT [acno], [username], [rdate] FROM [customer]">
</asp:SqlDataSource>
Default.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
GridView1.SelectedIndex = int.Parse(txtindex.Text);
int aid = Convert.ToInt32(GridView1.DataKeys[GridView1.SelectedIndex].Values[0]);
Response.Redirect("details.aspx?acno{0}");
}
details.aspx.cs
`
protected void Page_Load(object sender, EventArgs e)
{
int id =int.Parse( Request.QueryString["acno"]);
con.Open();
SqlCommand cmd=new SqlCommand("select acno,username,states,district,fname,lname from customer where acno='"+id+"'",con);
SqlDataReader dr;
dr=cmd.ExecuteReader();
while(dr.Read())
{
Label1.Text=dr[0].ToString();
Label2.Text=dr[1].ToString();
Label3.Text=dr[2].ToString();
Label4.Text=dr[3].ToString();
Label5.Text=dr[4].ToString();
Label6.Text=dr[5].ToString();
}
con.Close();
}
答案 0 :(得分:3)
int index = int.Parse(txtindex.Text);
int aid = Convert.ToInt32(GridView1.DataKeys[index].Value.ToString());
Response.Redirect(string.Format("details.aspx?acno={0}", aid));
最好使用int.TryParse
检查用户输入
int index,aid;
if (int.TryParse(txtindex.Text, out index) &&
int.TryParse((GridView1.DataKeys[index].Value.ToString()) , out aid))
{
Response.Redirect(string.Format("details.aspx?acno={0}", aid));
}