2010-09-17 81 views
6

我有此代碼用於填充基於小區一個gridview防止空的GridView數據

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) 
    { 

     txtComment.Text = row.Cells[14].Text.Trim(); 

    } 

它顯示 在txtComment文本框的選定行中的文本框如果細胞[ 14]沒有數據。

當選定行的單元中沒有數據時,是否有辦法阻止 出現?


編輯 我嘗試這樣做,也沒有工作

if (row.Cells[14].Text.Trim().Length > 1) 
{ 
    txtComment.Text = row.Cells[14].Text.Trim(); 
} 
else 
{ 
    txtComment.Text = row.Cells[14].Text = ""; 
} 

========================= ==================================================================================

這工作

if (row.Cells[14].Text.Trim()!=" ") 
{ 
    txtComment.Text = row.Cells[14].Text.Trim(); 
} 
else 
{ 
    txtComment.Text = row.Cells[14].Text = ""; 
} 
+0

你有沒有試過'row.Cells [14] .Text = string.Empty;'或'=「」;'? – 2010-09-17 18:18:45

+0

我試了兩個=字符串。空的;和=「」;並且我仍然收到了 – 2010-09-17 18:30:14

回答

4

問題是,您正在訪問HTML單元格的Text屬性,而不是第e數據列。 gridview需要在空表格單元中顯示 ,以便該表格單元在呈現給某些瀏覽器時仍可見。這是因爲HTML並且與您的數據或代碼沒有任何關係;

,你應該做的事情是這樣的:

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    DataRow myRow = (DataRow)GridView1.SelectedRow.DataItem; 
    txtComment.Text = myRow[14]; 
} 

用於訪問數據項屬性的格式將是基於什麼的DataItem實際上是,你可以把它轉換到有一點不同適合您的數據源的對象類型,然後相應地訪問其屬性。

編輯:我改變了示例代碼來演示將DataItem屬性轉換爲DataRow對象。您需要將其轉換爲您作爲數據源提供的任何類型。我希望這更清楚。

+0

當我嘗試使用時,出現此錯誤消息「無法將[]的索引應用於'object'類型的表達式」 – 2010-09-17 19:16:41

+0

@JoshuaSlocum:請參閱上面的編輯,您需要將DataItem強制轉換爲無論什麼類型的對象被用作數據源。 – CodingGorilla 2010-09-17 21:00:11

10

我也有過這樣一個問題,我發現這太有用:

txtComment.Text = row.Cells[14].Text.Replace(" ", ""); 

我希望它可以幫助你:)

+0

不好的解決方案...有很多其他更好的工作... – elle0087 2017-09-19 07:18:11

2

有沒有需要編寫任何代碼,只需添加HtmlEncode =「false」到Boundfield。

7

使用NullDisplayText =」「

 <asp:BoundField DataField="EmployeeName" HeaderText="Name" NullDisplayText=" "/> 
+0

乾淨,適合我。 – ZeeProgrammer 2017-08-10 18:40:57

2

使用此:

Server.HtmlDecode() 

例如:

txtComment.Text = Server.HtmlDecode(row.Cells[14].Text); 

它處理的不僅僅是空間,還有其他的轉換像符號(& )等。