2016-12-14 18 views
0

我收到異常'dr [「hylValue」]'拋出'System.ArgumentException'類型的異常。什麼可以是在ItemDataBound事件中獲取hylValue和hylName的可能方法。列「hylValue」不屬於表

public partial class WebForm1 : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     string hylValue = "https://www.google.co.in/"; 
     string hylName = "Google"; 
     DataTable dt = new DataTable(); 
     DataRow dr = dt.NewRow(); 
     dr["hylValue"] = hylValue.Split(new string[] {"~#~"}, StringSplitOptions.None); 
     dr["hylName"] = hylName.Split(new string[] {"~#~"},StringSplitOptions.None); 
     dt.Rows.Add(dr); 
     Repeater1.DataSource = dt; 
     Repeater1.DataBind(); 
    } 

    protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e) 
    { 
     if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) 
     { 
      DataTable tbl = (DataTable)e.Item.DataItem; 
      HyperLink hylFileUpload1 = (HyperLink)e.Item.FindControl("HyperLink1"); 
      hylFileUpload1.Text = tbl.Rows[0]["hylValue"].ToString(); 
      hylFileUpload1.NavigateUrl = tbl.Rows[0]["hylName"].ToString(); 
     } 
    } 
} 

這是我的aspx代碼

<body> 
<form id="form1" runat="server"> 
<div> 
    <a href="mailto:[email protected]" target="_blank">Sumit Patil</a> 
    <br /><br /> 
    <asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound"> 
     <ItemTemplate> 
        <asp:HyperLink ID="HyperLink1" runat="server"></asp:HyperLink> 
     </ItemTemplate> 
    </asp:Repeater> 
</div> 
</form> 

回答

0

首先,你的數據表沒有任何列,但你要訪問列hylValuehylName。訪問它們之前,它們添加到您的表,這樣的:

 string hylValue = "https://www.google.co.in/"; 
     string hylName = "Google"; 
     DataTable dt = new DataTable(); 
     dt.Columns.Add("hylValue", typeof(string)); 
     dt.Columns.Add("hylName", typeof(string)); 
     DataRow dr = dt.NewRow(); 

其次,在ItemDataBoundDataItem不是DataTable,但DataRowView,所以你的代碼應該是這個樣子:

if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) 
     { 
      DataRowView tbl = (DataRowView)e.Item.DataItem; 
      HyperLink hylFileUpload1 = (HyperLink)e.Item.FindControl("HyperLink1"); 
      hylFileUpload1.Text = tbl["hylValue"].ToString(); 
      hylFileUpload1.NavigateUrl = tbl["hylName"].ToString(); 
     }