我的情况是我正在动态创建一个数据表,并将该数据表添加到数据集并在网格视图中显示它。我想在每行的末尾添加一个“添加到图表”按钮,该按钮将具有其他功能。
我用于创建动态数据表的代码:
try
{
response = client.query(a);
///List of fields
var fields = response.@return.fields;
//loop through each column
foreach (String column in fields)
{
dtservice.Columns.Add(column);
}
///List of value return as list of object
var values = response.@return.values.ToList();
///get the first object from the list of object
foreach (object item in values)
{
if (item == null) continue;
foreach (PropertyInfo property in item.GetType().GetProperties())
{
// do something with the property
List<string> valueList = (List<string>)(property.GetValue(item, null));
dtservice.Rows.Add(valueList.ToArray());
}
}
}
catch (Exception error)
{
var b = error.ToString();
}
//create dataset
DataSet test= new DataSet();
test.Tables.Add(dtservice);
return test;
}
我尝试使用下面的代码,但单击后按钮消失。
protected void WorkList_RowDataBound(object sender, GridViewRowEventArgs e)
{
// CHECK IF ROW IS NOT IN EDIT MODE
if (e.Row.RowType == DataControlRowType.DataRow)
{
// CREATE A Button
Button btn = new Button();
btn.ID = "btnEstados";
btn.Text = "Estados";
// ADD BUTTON TO EACH ROW IN 2ND COLUMN
e.Row.Cells[7].Controls.Add(btn);
}
}
第二个问题现在我能够获得每一行的按钮,但是使用下面的代码,我得到的列数等于1。它实际上只读取html中添加的静态列,而不读取生成的那一列动态地
//adding column to datatable
for (int row = 0; row < test.Columns.Count - 1; row++)
{
ServiceName.Columns.Add(test.HeaderRow.Cells[row].Text, typeof(string));
}
答案 0 :(得分:0)
这是在Gridview中添加按钮的另一种方式。
<asp:GridView ID="WorkList" runat="server" Width="100%" AutoGenerateColumns="false" AllowPaging="false" AllowSorting="false"
EmptyDataText="No Record Found"
OnRowCreated="WorkList_RowCreated"
OnRowCommand="WorkList_RowCommand"
OnRowCancelingEdit="WorkList_RowCancelingEdit"
OnRowEditing="WorkList_RowEditing">
<AlternatingRowStyle CssClass="alt" BackColor="#CCFF99"></AlternatingRowStyle>
<Columns>
<asp:ButtonField ButtonType="Button" CommandName="Estados" HeaderText="" ShowHeader="True" Text="Estados" ItemStyle-Width="30px" />
</Columns>
<HeaderStyle BackColor="#808080" ForeColor="#48D1CC" />
</asp:GridView>
在WorkList_RowCommand中:
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow gvRow = WorkList.Rows[index];
WorkList.Rows[index];
if (e.CommandName == "Estados")
{
//your code here like `gvRow.Cells[0].Text`
}
确保后面的代码中存在WorkList
声明的属性。
希望有帮助。