我已经尝试了很多,并已达到死胡同。databind gridview填充在代码后面
我有一个在一个页面上显示多个gridviews,所有这些都动态填充。
我想通过动态填充gridview并显示它们,但我无法得到如何修改这些值并显示它们,因为我想要的方式。
这里是代码。对于.aspx页面中
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">
<asp:Panel ID="Panel1" runat="server" ScrollBars ="Auto" Height="500px" BorderColor="#003399" BorderWidth="3px">
</asp:Panel>
</asp:Content>
这里是.aspx.cs
for (int j = 0; j < 5; j++)
{
GridView Grid = new GridView();
ArrayList machID = new ArrayList();
ArrayList machName = new ArrayList();
Grid.ID = machGrps[j].ToString();
Grid.AllowSorting = true;
Grid.CellSpacing = 2;
Grid.GridLines = GridLines.None;
Grid.Width = Unit.Percentage(100);
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(Session["ConnectionStringSQL"].ToString());
connection.Open();
SqlCommand sqlCmd = new SqlCommand("select MachineID, MachineName from Machines", connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
connection.Close();
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
machID.Add(dt.Rows[i]["MachineID"].ToString());
machName.Add(dt.Rows[i]["MachineName"].ToString());
}
DataTable taskTable = new DataTable();
taskTable.Columns.Add("MachineID");
taskTable.Columns.Add("MachineName");
if (machID.Count != 0)
{
for (int i = 0; i < machID.Count; i++)
{
DataRow tableRow = taskTable.NewRow();
tableRow["MachineID"] = machID[i];
tableRow["MachineName"] = machName[i];
taskTable.Rows.Add(tableRow);
}
}
Session["TaskTable"] = taskTable;
Grid.DataSource = Session["TaskTable"];
Grid.DataBind();
Label label = new Label();
label.Text = "Machine Grp" + Grid.ID;
Panel1.Controls.Add(label);
Panel1.Controls.Add(Grid);
}
}
注意此功能的代码下面的代码可以按我直接填充在GridView从表中不再被DONE:
如果从.aspx页面调用ondatabound =“GridView1_DataBound”,我曾经这样修改:
数据绑定代码如下所示:
protected void GridView1_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow myRow in GridView1.Rows)
{
//this is where ID is stored in an label template
Label Label3 = (Label)myRow.FindControl("Label3");
int val = Convert.ToInt32(Label3.Text);
Image Image5 = (Image)myRow.FindControl("Image5");
if (Convert.ToInt32(Label3.Text) < 0)
{
Image5.ImageUrl = "~/NewFolder1/warning_16x16.gif";
}
else
{
Image5.ImageUrl = "~/NewFolder1/1258341827_tick.png";
}
}
}
e.Row.RowType == DataControlRowType.DataRow如你所说将采取整个行,但我如何修改该行中的值。因为你可以看到我已经动态地填充了它。我的意思是首先我有标签来寻找,因为它包含了ID,但现在我没有没有标签找到 – user175084 2010-11-16 22:36:18
drachenstern ..这就是我所说的没有标签3控件,因为那里我没有创建gridview HTML页面,所以当它试图做到这一点“Label Label3 =(Label)e.Row.FindControl(”Label3“);”它什么也得不到。 – user175084 2010-11-16 22:54:29
@ user175084〜嗯,我想我看到了问题。你知道你想从桌子上看到什么细胞吗?(例如你可以用Firebug找到),那么你可以使用'e.Row.Cells [0] .Text'而不是'Label3.Text'。我刚刚意识到你正在寻找一个你从未明确分配的标签。如果您想使用数据表中的值,您也可以使用'e.Row.DataItem'中'Row'的'DataItem'。 – jcolebrand 2010-11-16 22:58:26