我已經嘗試了很多,並已達到死衚衕。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