【发布时间】:2018-02-18 00:23:36
【问题描述】:
这是我的代码:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt=PrepareFirstGridViewRow(); //function below
DataRow dr = dt.NewRow();
dr["Index"] = index;
index++;
dr["Telephone"] = Telephone;
dr["Amount"] = Amount;
dr["Comment"] = Comment;
Button BTN = new Button();
BTN.Click += GridButton_Click;
BTN.OnClientClick = "GridButton_Click";
BTN.Text = "Sell";
BTN.Attributes.Add("CId", j.ToString());
BTN.Style.Value = "display:inline-block;";
BTNF.ButtonType = ButtonType.Button;
dr["Sell"] = BTN;
dt.Rows.Add(dr);
ContractsGrid.DataSource = dt;
ContractsGrid.DataBind();
ContractsGrid.Columns.Add(new DataControlField);
connection.Close();
}
还有函数准备:
private DataTable PrepareFirstGridViewRow()
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Index", typeof(string)));
dt.Columns.Add(new DataColumn("Telephone", typeof(string)));
dt.Columns.Add(new DataColumn("Amount", typeof(string)));
dt.Columns.Add(new DataColumn("Comment", typeof(string)));
dt.Columns.Add(new DataColumn("Sell", typeof(Button)));
return dt;
}
一切正常,除了在最后一列中插入按钮,它根本不出现(标题和按钮都没有)。当我将("Sell", typeof(Button)) 替换为("Sell", typeof(string)) 和dr["Sell"] = "something"; 时,网格已正确创建。
问题很简单:为什么?
我尝试了以下解决方案:
protected void Page_Load(object sender, EventArgs e)
{
try
{
Button btn = new Button();
btn.Text = "Click";
btn.ID = "btn_click";
btn.Click += new EventHandler(btnevent_Click);
btn.OnClientClick = "Hello('" + "a" + "')";
form1.Controls.Add(btn);
}
catch (Exception)
{ }
}
上面的代码虽然在 page_load 事件中,但在页面事件上生成按钮。所以问题一定不是事件,而是网格视图。
下面的代码也可以正常工作,但是按钮被添加到整个网格中(我意识到这一点)。所以这不是关于事件,而是将按钮插入网格。
Button BTNo = new Button();
BTNo.Click += GridButton_Click;
BTNo.OnClientClick = "GridButton_Click";
BTNo.Text = "Sell";
BTNo.Attributes.Add("CId", "1");
BTNo.Style.Value = "display:block;";
ContractsGrid.DataSource = dt;
ContractsGrid.DataBind();
ContractsGrid.Controls.Add(BTNo);
connection.Close();
【问题讨论】:
标签: asp.net button gridview webforms