我需要知道如何允许 Gridview 列接受 LinkButton。默认情况下,GridView Column 设置为接受 TextBox 控件,但我需要有一个 LinkButton 控件。我的代码是:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.IO;
using System.Data.Common;
using System.Globalization;
namespace GridView_Tutorial
{
public partial class GridView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=Mehdi-PC\\SqlExpress; Initial Catalog=PIMS; Integrated Security=true");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT cat_id, cat_name FROM quest_categories", con);
DataTable dt = new DataTable();
da.Fill(dt);
//add a blank row to returned DataTable
DataRow dr = dt.NewRow();
dt.Rows.InsertAt(dr, 0);
//creating the first row of Gridview to be editable
GridView1.EditIndex = 0;
//Data Sourcing and binding
GridView1.DataSource = dt;
GridView1.DataBind();
//Changing the Text for Inserting a New Record
((LinkButton)GridView1.Rows[0].Cells[0].Controls[0]).Text = "Insert";
if (con != null)
{
con.Close();
}
}
}
}
以下代码行抛出错误:
((LinkButton)GridView1.Rows[0].Cells[0].Controls[0]).Text = "Insert";
错误信息是:
InvalidCastException is unhandled by the user.
Unable to cast object of type 'System.Web.UI.WebControls.TextBox' to type 'System.Web.UI.WebControls.LinkButton'.
当我从以下位置更改代码时:
((LinkButton)GridView1.Rows[0].Cells[0].Controls[0]).Text = "Insert";
至
((TextBox)GridView1.Rows[0].Cells[0].Controls[0]).Text = "Insert";
错误消失,代码在数据表中插入一个文本框。
请帮我插入 LinkButton 而不是 TextBox。
问候