我正在尝试从代码后面绑定gridview。其中一列包含一个按钮。该按钮的文本应根据行中加载的内容而更改。例如,根据内容,该按钮应显示发布或取消发布。这就是我所做的。
gridview的aspx代码:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:BoundField HeaderText="Name" DataField="Name">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Sub Category" DataField="Sub Category"></asp:BoundField>
<asp:ImageField HeaderText="Image" DataImageUrlField="Image" ControlStyle-Height="39px"
ControlStyle-Width="150px">
</asp:ImageField>
<asp:BoundField HeaderText="Start Date" DataField="Start Date"></asp:BoundField>
<asp:BoundField HeaderText="Expiry Date" DataField="Expiry Date"></asp:BoundField>
<asp:ButtonField HeaderText="Status" DataTextField="Status" ButtonType="Button" CommandName="publishButton_Click" />
</Columns>
</asp:GridView>
这是我背后的代码:
protected void Page_Load(object sender, EventArgs e){
GridView1.DataSource = fillOfferGridView(nodeid);
GridView1.DataBind();
}
DataTable fillOfferGridView(int nodeId)
{
Document next = new Document(nodeId);
Button bf = new Button();
DataTable dtOfferDetails = new DataTable();
dtOfferDetails.Columns.Add("Name", typeof(string));
dtOfferDetails.Columns.Add("Sub Category", typeof(string));
dtOfferDetails.Columns.Add("Image", typeof(string));
dtOfferDetails.Columns.Add("Start Date", typeof(string));
dtOfferDetails.Columns.Add("Expiry Date", typeof(string));
dtOfferDetails.Columns.Add("Status", typeof(Button));
foreach (Document offer in next.Children)
{
DataRow dr = dtOfferDetails.NewRow();
//string myOfferName = offer.GetProperty("offerName").Value;
//string offerNodeName = offer.Name;
//string offerurl = offer.NiceUrl;
//string offerType = offer.GetProperty("offerType").Value;
//string offerImage = offer.GetProperty("offerImage").Value;
dr["Name"] = offer.getProperty("offerName").Value;
dr["Sub Category"] = offer.getProperty("offerType").Value;
dr["Image"] = ResolveUrl(offer.getProperty("offerImage").ToString());
dr["Start Date"] = offer.getProperty("offerLaunchDate").Value;
dr["Expiry Date"] = offer.getProperty("offerExpiryDate").Value;
if (offer.Published == true)
{
bf.Text = "Unpublish";
}
else
{
bf.Text = "Publish";
}
dr["Status"] = bf;
dtOfferDetails.Rows.Add(dr);
}
return dtOfferDetails;
}
但是当我运行代码而不是所需的文本时,我会在按钮上获得 system.web.ui.webcontrols.button 。我做错了什么?
答案 0 :(得分:2)
修改此行
dr["Status"] = bf;
到
dr["Status"] = bf.Text;
答案 1 :(得分:1)
dr["Status"] = bf.Text;
如果你在Status字段中放置按钮,DataGrid只调用它的ToString()方法,结果你得到了system.web.ui.webcontrols.button文本而不是按钮标题。
更多。您不需要在代码中创建新Button。只需写下:
if (offer.Published == true)
{
dr["Status"] = "Unpublish";
}
else
{
dr["Status"] = "Publish";
}
答案 2 :(得分:1)
这一行必须是:
dr["Status"] = bf.Text;