无法将类型为“System.Web.UI.WebControls.HyperLink”的对象强制转换为类型“System.Web.UI.WebControls.

xiaomo1133 2012-05-11 01:36:34
无法将类型为“System.Web.UI.WebControls.HyperLink”的对象强制转换为类型“System.Web.UI.WebControls.TextBox”。
说明: 执行当前 Web 请求期间,出现未经处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。

异常详细信息: System.InvalidCastException: 无法将类型为“System.Web.UI.WebControls.HyperLink”的对象强制转换为类型“System.Web.UI.WebControls.TextBox”。

源错误:

行 69: string empID = this.GridView1.DataKeys[e.RowIndex].Value.ToString();
行 70: //注意:以下cells的索引值可能会随着设计的进行发生变化,关键是正确地检测出 “公司名称”和 “联系人姓名”两个字段的索引值!!!
行 71: string companyname = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[5].Controls[0])).Text.ToString().Trim();
行 72: string 联系人姓名 = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[6].Controls[0])).Text.ToString().Trim();
行 73: SqlConnection con = DB.createCon();


源文件: e:\MYASPNET\st13\Default.aspx.cs 行: 71

堆栈跟踪:

[InvalidCastException: 无法将类型为“System.Web.UI.WebControls.HyperLink”的对象强制转换为类型“System.Web.UI.WebControls.TextBox”。]
_Default.GridView1_RowUpdating(Object sender, GridViewUpdateEventArgs e) in e:\MYASPNET\st13\Default.aspx.cs:71
System.Web.UI.WebControls.GridView.OnRowUpdating(GridViewUpdateEventArgs e) +139
System.Web.UI.WebControls.GridView.HandleUpdate(GridViewRow row, Int32 rowIndex, Boolean causesValidation) +808
System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) +855
System.Web.UI.WebControls.GridView.OnBubbleEvent(Object source, EventArgs e) +95
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37
System.Web.UI.WebControls.GridViewRow.OnBubbleEvent(Object source, EventArgs e) +121
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37
System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e) +125
System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +169
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +9
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +176
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563

...全文
662 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
xiaomo1133 2012-05-12
  • 打赏
  • 举报
回复
无法将类型为“System.Web.UI.LiteralControl”的对象强制转换为类型“System.Web.UI.WebControls.TextBox”。
说明: 执行当前 Web 请求期间,出现未经处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。

异常详细信息: System.InvalidCastException: 无法将类型为“System.Web.UI.LiteralControl”的对象强制转换为类型“System.Web.UI.WebControls.TextBox”。

源错误:

行 74: //联系人姓名 =((TextBox)(GridView1.Rows[2].Cells[1].Controls[0]).FindControl("TextBox2")).Text.ToString().Trim());
行 75: companyname = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[1])).Text.ToString().Trim();
行 76: 联系人姓名 = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim();
行 77: SqlConnection con = DB.createCon();
行 78: SqlCommand cmd = new SqlCommand("update 供应商 set 公司名称= '" + companyname + "', 联系人姓名='" + 联系人姓名 + "' where 供应商ID='" + empID + "'", con);

xiaomo1133 2012-05-12
  • 打赏
  • 举报
回复
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Debug="true" %>

<!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>
<style type="text/css">
.style1
{
text-align: center;
font-size: x-large;
}
</style>
<link href="StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body >
<link href="StyleSheet.css" rel="stylesheet" type="text/css" />
<form id="form1" runat="server" >
<div class="style1" align="center">
<strong> 供货商列表<br />
<br />
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AutoGenerateColumns="False" BackColor="White" BorderColor="#E7E7FF"
BorderStyle="None" BorderWidth="1px" CellPadding="3" HorizontalAlign="Center"
onpageindexchanging="GridView1_PageIndexChanging"
onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating" onsorting="GridView1_Sorting"
DataKeyNames="供应商ID"
onselectedindexchanged="GridView1_SelectedIndexChanged"
onrowcancelingedit="GridView1_RowCancelingEdit">
<AlternatingRowStyle BackColor="#F7F7F7" />
<PagerTemplate>
<asp:LinkButton ID="lbFirst" runat="server" CausesValidation="False" CommandArgument="First" CommandName="Page">首页</asp:LinkButton>
<asp:LinkButton ID="lbPrev" runat="server" CausesValidation="False" CommandArgument="Prev" CommandName="Page">上一页</asp:LinkButton>
<asp:LinkButton ID="lbNext" runat="server" CausesValidation="False" CommandArgument="Next" CommandName="Page">下一页</asp:LinkButton>
<asp:LinkButton ID="lbLast" runat="server" CausesValidation="False" CommandArgument="Last" CommandName="Page">尾页</asp:LinkButton>
第<asp:Label ID="Label2" runat="server" Text="<%#((GridView)Container.Parent.Parent).PageIndex + 1 %>"></asp:Label>页
共<asp:Label ID="Label1" runat="server" Text="<%# ((GridView)Container.Parent.Parent).PageCount %>"></asp:Label>页
跳到<asp:TextBox ID="tbPage" runat="server" Text="<%# ((GridView)Container.Parent.Parent).PageIndex + 1 %>" Width="27px"></asp:TextBox>
<asp:LinkButton ID="lbGO" runat="server" CausesValidation="False" CommandArgument="-1" CommandName="Page" Text="GO" OnClick="lbGO_Click"></asp:LinkButton>
</PagerTemplate>
<Columns>
<asp:TemplateField HeaderText="供应商ID" SortExpression="供应商ID">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("供应商ID") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("供应商ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="公司名称" SortExpression="公司名称">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("公司名称") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("公司名称") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="联系人姓名" SortExpression="联系人姓名">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("联系人姓名") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label10" runat="server" Text='<%# Bind("联系人姓名") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="地址" SortExpression="地址">
<EditItemTemplate>
<asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("地址") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label60" runat="server" Text='<%# Bind("地址") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
<asp:HyperLinkField DataNavigateUrlFields="供应商ID" DataNavigateUrlFormatString="showDetails.aspx?empID={0}" DataTextField="供应商ID" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField></asp:TemplateField>
</Columns>
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<SortedAscendingCellStyle BackColor="#F4F4FD" />
<SortedAscendingHeaderStyle BackColor="#5A4C9D" />
<SortedDescendingCellStyle BackColor="#D8D8F0" />
<SortedDescendingHeaderStyle BackColor="#3E3277" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:FPNWINDConnectionString %>"
DeleteCommand="DELETE FROM [供应商] WHERE [供应商ID] = @供应商ID"
InsertCommand="INSERT INTO [供应商] ([供应商ID], [公司名称], [联系人姓名], [联系人头衔], [地址], [城市], [地区], [邮政编码], [国家], [电话], [传真]) VALUES (@供应商ID, @公司名称, @联系人姓名, @联系人头衔, @地址, @城市, @地区, @邮政编码, @国家, @电话, @传真)"
SelectCommand="SELECT [供应商ID], [公司名称], [联系人姓名], [联系人头衔], [地址], [城市], [地区], [邮政编码], [国家], [电话], [传真] FROM [供应商]"
UpdateCommand="UPDATE [供应商] SET [公司名称] = @公司名称, [联系人姓名] = @联系人姓名, [联系人头衔] = @联系人头衔, [地址] = @地址, [城市] = @城市, [地区] = @地区, [邮政编码] = @邮政编码, [国家] = @国家, [电话] = @电话, [传真] = @传真 WHERE [供应商ID] = @供应商ID">
<DeleteParameters>
<asp:Parameter Name="供应商ID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="供应商ID" Type="Int32" />
<asp:Parameter Name="公司名称" Type="String" />
<asp:Parameter Name="联系人姓名" Type="String" />
<asp:Parameter Name="联系人头衔" Type="String" />
<asp:Parameter Name="地址" Type="String" />
<asp:Parameter Name="城市" Type="String" />
<asp:Parameter Name="地区" Type="String" />
<asp:Parameter Name="邮政编码" Type="String" />
<asp:Parameter Name="国家" Type="String" />
<asp:Parameter Name="电话" Type="String" />
<asp:Parameter Name="传真" Type="String" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="公司名称" Type="String" />
<asp:Parameter Name="联系人姓名" Type="String" />
<asp:Parameter Name="联系人头衔" Type="String" />
<asp:Parameter Name="地址" Type="String" />
<asp:Parameter Name="城市" Type="String" />
<asp:Parameter Name="地区" Type="String" />
<asp:Parameter Name="邮政编码" Type="String" />
<asp:Parameter Name="国家" Type="String" />
<asp:Parameter Name="电话" Type="String" />
<asp:Parameter Name="传真" Type="String" />
<asp:Parameter Name="供应商ID" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:Label ID="Label3" runat="server"></asp:Label>
<br />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="ok" /> 
<asp:Button ID="Button3" runat="server" onclick="Button3_Click" Text="清除所选内容" />
<br />
<br />
<asp:DropDownList ID="DropDownList1" runat="server"> </asp:DropDownList> 
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="删除" />
<br />
</strong>
</div>
</form>
</body>
</html>
暖枫无敌 2012-05-12
  • 打赏
  • 举报
回复
那现在是怎么回事?
报错?结果不对??
究竟是哪样,请描述一下
xiaomo1133 2012-05-12
  • 打赏
  • 举报
回复
using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Security;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
public DataSet ds = new DataSet();//建立数据集对象
protected void Page_Load(object sender, EventArgs e)
{
// 在此处放置用户代码以初始化页面
if (!this.IsPostBack)
{
BindGrid();
}
this.GridView1.AllowPaging = true;
this.GridView1.AllowSorting = true;
}

private void BindGrid()
{
//数据绑定方法
SqlConnection con = DB.createCon();
SqlDataAdapter sda = new SqlDataAdapter("select * from 供应商", con);
sda.Fill(ds, "emp"); //装填数据集DataSet
//和更新按钮有关,需要设置主键*****************
this.GridView1.DataKeyNames = new string[] { "供应商ID" };//索引关键字
//************************************************
this.GridView1.DataSource = ds.Tables["emp"].DefaultView;
this.GridView1.DataBind();

DropDownList1.DataSource = ds.Tables["emp"].DefaultView;
DropDownList1.DataTextField = "公司名称";//下拉列表框显示内容
DropDownList1.DataValueField = "供应商ID";//下拉列表框的值内容
DropDownList1.DataBind();
}
protected void lbGO_Click(object sender, EventArgs e)
{
GridViewRow pagerRow = GridView1.BottomPagerRow;
TextBox pageNum = pagerRow.Cells[0].FindControl("tbPage") as TextBox;
if (pageNum.Text != null)
{
if (Convert.ToInt32(pageNum.Text) > 0 && Convert.ToInt32(pageNum.Text)<= GridView1.PageCount)
GridView1.PageIndex = Convert.ToInt32(pageNum.Text) - 1;
}
BindGrid(); //调用上面的BindGrid()绑定
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
if (e.NewPageIndex >= 0 && e.NewPageIndex < GridView1.PageCount)
this.GridView1.PageIndex = e.NewPageIndex;
BindGrid(); //调用上面的BindGrid()绑定
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
this.GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string companyname="" ;
string 联系人姓名="";
// 返回选定行的主键值
string empID = this.GridView1.DataKeys[e.RowIndex].Value.ToString();
//注意:以下cells的索引值可能会随着设计的进行发生变化,关键是正确地检测出 “公司名称”和 “联系人姓名”两个字段的索引值!!!
//companyname = ((TextBox)(GridView1.Rows[1].Cells[1].Controls[0]).FindControl("TextBox1")).Text.ToString().Trim());
//联系人姓名 =((TextBox)(GridView1.Rows[2].Cells[1].Controls[0]).FindControl("TextBox2")).Text.ToString().Trim());
companyname = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[1])).Text.ToString().Trim();
联系人姓名 = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim();
SqlConnection con = DB.createCon();
SqlCommand cmd = new SqlCommand("update 供应商 set 公司名称= '" + companyname + "', 联系人姓名='" + 联系人姓名 + "' where 供应商ID='" + empID + "'", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
this.GridView1.EditIndex = -1;
BindGrid();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
// 返回选定行的主键值
string SupID=this.GridView1.DataKeys[e.RowIndex].Value.ToString();
SqlConnection con=DB.createCon();
SqlCommand cmd=new SqlCommand("delete 供应商 where 供应商ID='"+SupID+"'",con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
this.GridView1.EditIndex=-1;
BindGrid();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//单向排序设置
//ViewState["Order"] = "ASC"; //按递增排序,递减为:DESC
//上行代码要放在此事件以外,可放在page_load事件中
//双向排序设置:如果原来是降序则改为升序,反之亦然
if((string)ViewState["Order"]=="DESC")
ViewState["Order"] = "ASC";
else
ViewState["Order"] = "DESC";
SqlConnection con=DB.createCon(); //连接 FPNWIND 库
SqlDataAdapter sda = new SqlDataAdapter("select * from 供应商",con);
//DataSet对象 ds 已经在前面定义);
sda.Fill(ds,"emp");
//设定默认视图DefaultView来排序
ds.Tables["emp"].DefaultView.Sort=e.SortExpression+" "+ViewState["Order"].ToString();
this.GridView1.DataSource=ds.Tables["emp"].DefaultView;
this.GridView1.DataBind();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow dl in this.GridView1.Rows)
{
CheckBox chk = (CheckBox)dl.FindControl("chkSelect");
if (chk.Checked)
{
this.Label3.Text += this.GridView1.DataKeys[dl.RowIndex].Value.ToString()+ ", ";
}
}
}
protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection con=DB.createCon();
SqlCommand cmd = new SqlCommand("delete from 供应商 where 供应商ID='"
+DropDownList1.SelectedItem.Value+"'",con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
this.GridView1.EditIndex = -1;
this.BindGrid();
}
protected void Button3_Click(object sender, EventArgs e)
{
this.Label3.Text = "";
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
this.GridView1.EditIndex = -1;
BindGrid();
}
}
xiaomo1133 2012-05-12
  • 打赏
  • 举报
回复
网上说可能是标签之间空间有空格。。。但不是。
xiaomo1133 2012-05-12
  • 打赏
  • 举报
回复
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string companyname="" ;
string 联系人姓名="";
// 返回选定行的主键值
string empID = this.GridView1.DataKeys[e.RowIndex].Value.ToString();
//注意:以下cells的索引值可能会随着设计的进行发生变化,关键是正确地检测出 “公司名称”和 “联系人姓名”两个字段的索引值!!!
//companyname = ((TextBox)(GridView1.Rows[1].Cells[1].Controls[0]).FindControl("TextBox1")).Text.ToString().Trim());
//联系人姓名 =((TextBox)(GridView1.Rows[2].Cells[1].Controls[0]).FindControl("TextBox2")).Text.ToString().Trim());
companyname = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[1])).Text.ToString().Trim();
联系人姓名 = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim();
SqlConnection con = DB.createCon();
SqlCommand cmd = new SqlCommand("update 供应商 set 公司名称= '" + companyname + "', 联系人姓名='" + 联系人姓名 + "' where 供应商ID='" + empID + "'", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
this.GridView1.EditIndex = -1;
BindGrid();
}
谈阿大 2012-05-12
  • 打赏
  • 举报
回复
我觉得,HyperLink不能转换成TextBox ,但是应该都能转换成objet类型,所有都是objet类派生的。
楼主想要做什么事情,如果光取值何必转换呢。
暖枫无敌 2012-05-12
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 的回复:]
我试过了,不可以。。。。开始我以为Cells的序号有问题,但试了,不行。。。。。。。。。。。。
[/Quote]

序号是从0开始的,你只要没有弄错的话,并且该列确实是HyperLink的话,那样写就不会有错。

那现在又报什么错呢?
xiaomo1133 2012-05-12
  • 打赏
  • 举报
回复
我试过了,不可以。。。。开始我以为Cells的序号有问题,但试了,不行。。。。。。。。。。。。
暖枫无敌 2012-05-12
  • 打赏
  • 举报
回复
无法将类型为“System.Web.UI.WebControls.HyperLink”的对象强制转换为类型“System.Web.UI.WebControls.TextBox”。

提示这么明显了,你的GridView单元格是一个HyperLink,而你却将他转换成TextBox,无法强制转换。

string companyname = ((HyperLink)(GridView1.Rows[e.RowIndex].Cells[5].Controls[0])).Text.ToString().Trim();
xiaomo1133 2012-05-12
  • 打赏
  • 举报
回复
还是有问题..........
companyname = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[5].Controls[0])).Text.ToString().Trim();
联系人姓名 = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[6].Controls[0])).Text.ToString()Trim(); 错的 是这两句
没明白楼主的意思
孟子E章 2012-05-11
  • 打赏
  • 举报
回复
GridView1.Rows[e.RowIndex].Cells[5].Controls[0])不是一个TextBox,你最好使用
GridView1.Rows[e.RowIndex].FindControl("TextBoxID") as TextBox

62,267

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧