在GridView中获取ASP.NET HyperLinkField的文本
我正在尝试在GridView的OnRowDelete事件中获取HyperLinkField的文本(HyperLinkField的文本是我想删除的行的主键)。 我知道您无法使用我下面的代码获取文本; 它仅适用于BoundFields(对于HyperLinkFields,字符串为“”)。 但是,我一直无法找到获得此文本的工作答案。 如何从HyperLinkField获取显示的文本? (VS2010 w / ASP.NET 4.0和C#)
谢谢阅读!
GridView设计
GridView填充代码
using (SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["***"].ConnectionString)) { // Initialize GridView and data teamGridView.AutoGenerateColumns = false; if (Convert.ToInt32(Session["UserLevel"]) > 0) { teamGridView.Columns[2].Visible = true; } SqlDataAdapter teamDataAdapter = new SqlDataAdapter(); DataSet teamDataSet = new DataSet(); if (Request["Team_Name"] == null) { // Show the list of teams if no specific team is requested teamDataAdapter.SelectCommand = new SqlCommand("[Team Select]", connection); teamDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure; teamDataAdapter.Fill(teamDataSet); teamGridView.DataSource = teamDataSet; teamGridView.DataBind(); } }
GridView OnRowDeleting代码
using (SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["***"].ConnectionString)) { SqlCommand teamDeleteCommand = new SqlCommand("[Team Delete]", connection); teamDeleteCommand.CommandType = CommandType.StoredProcedure; teamDeleteCommand.Parameters.Add("TeamName", SqlDbType.NVarChar, 50); teamDeleteCommand.Parameters[0].Value = teamGridView.Rows[e.RowIndex].Cells[0].Text; Response.Write(teamDeleteCommand.Parameters[0].Value); try { connection.Open(); teamDeleteCommand.ExecuteNonQuery(); } catch (SqlException ex) { throw new Exception("Team Deletion Error"); } }
代替
teamGridView.Rows[e.RowIndex].Cells[0].Text;
尝试
( (HyperLink) teamGridView.Rows[e.RowIndex].Cells[0].Controls[0] ).Text
无法避免建议您改变将所有SQL直接放在页面中的方式。 尝试依靠N层开发。 MSDN和asp.NET网站以及channel9.msdn都有很好的video开头。 另外, http://weblogs.asp.net/scottgu
((HyperLink)teamGridView.Rows[e.RowIndex].Cells[0].Controls[0] ).Text
将给出该字段的文本或显示值。 或者我们可以尝试
((HyperLink)teamGridView.Rows[e.RowIndex].Cells[0].Controls[0] ).NavigateUrl
获取目标链接。
另一种获取超链接文本值的替代方法:
Server.HtmlDecode((teamGridView.Rows[e.RowIndex].Cells[0].Controls[0] as HyperLink).Text)