Gridview 列が LinkButton を受け入れられるようにする方法を知る必要があります。デフォルトでは、GridView 列は 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";
エラーがなくなり、コードがデータテーブルにテキスト ボックスを挿入します。
TextBox の代わりに LinkButton を挿入するのを手伝ってください。
よろしく