我正在尝试在GridView的OnRowDelete事件中获取HyperLinkField的文本(HyperLinkField的文本是我想删除的行的主键).我知道您无法使用我下面的代码获取文本; 它仅适用于BoundFields(对于HyperLinkFields,字符串为"").但是,我一直无法找到获得此文本的工作答案.如何从HyperLinkField获取显示的文本?(VS2010 w/ASP.NET 4.0和C#)
谢谢阅读!
GridView设计
<asp:GridView ID="teamGridView" runat="server" CssClass="gridView" RowStyle-CssClass="rowStyle"
AlternatingRowStyle-CssClass="altRowStyle" HeaderStyle-CssClass="viewsHeader"
OnRowEditing="Team_OnRowEditing" OnRowDeleting="Team_OnRowDeleting" OnRowUpdating="Team_OnRowUpdating"
OnRowCancelingEdit="Team_OnRowCancelingEdit">
<Columns>
<asp:HyperLinkField HeaderText="Team Name" DataTextField="Team Name" DataNavigateUrlFields="Team Name"
DataNavigateUrlFormatString="Teams.aspx?Team_Name={0}" />
<asp:BoundField HeaderText="Team Captain" DataField="Team Captains" />
<asp:CommandField Visible="false" HeaderText="Commands" ShowEditButton="true" ShowDeleteButton="true" />
</Columns>
</asp:GridView>
Run Code Online (Sandbox Code Playgroud)
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();
}
}
Run Code Online (Sandbox Code Playgroud)
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");
}
}
Run Code Online (Sandbox Code Playgroud)
Mel*_*igy 22
代替
teamGridView.Rows[e.RowIndex].Cells[0].Text;
Run Code Online (Sandbox Code Playgroud)
尝试
( (HyperLink) teamGridView.Rows[e.RowIndex].Cells[0].Controls[0] ).Text
Run Code Online (Sandbox Code Playgroud)
无法避免建议您改变将所有SQL直接放在页面中的方式.尝试依靠N层开发.MSDN和asp.NET网站以及channel9.msdn都有很好的视频开头.另外,http://weblogs.asp.net/scottgu