2012-12-06 47 views
3

我在我的QueryString中傳遞十六進制值。我想將其轉換爲顏色以在網格視圖中的單元格中使用ForeColor。嘗試System.Drawing.ColorTranslator.FromHtml()System.Drawing.Color.FromArgb()沒有運氣。將十六進制字符串轉換爲彩色

我的查詢字符串的url編碼,這樣重要的部分看起來像:

QueryString...&color=%23AA4643 

下面是我曾嘗試.FromArg:

string sColor = Request.QueryString["color"]; // sColor is now #AA4643 
Int32 iColorInt = Convert.ToInt32(sColor,16); //Get error message - Could not find any recognizable digits 
Color curveColor = System.Drawing.Color.FromArgb(iColorInt); //Never makes it here 

這裏是我曾嘗試.FromHtml:

string sColor = Request.QueryString["color"]; 
System.Drawing.Color myColor = new System.Drawing.Color(); 
myColor = System.Drawing.ColorTranslator.FromHtml(sColor); 

在這種情況下,myColor被設置爲 - myColor =「{Name = ffaa4643,ARGB =(255,170,70,67)}」

但是當我去使用它,我得到一個錯誤:

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

任何和所有幫助非常感謝

回答

7

試試這個:

string sColor = Request.QueryString["color"]; // sColor is now #AA4643 
Int32 iColorInt = Convert.ToInt32(sColor.Substring(1),16); 
Color curveColor = System.Drawing.Color.FromArgb(iColorInt); 
+0

Thaks,那些通過了線它錯誤並將curveColor設置爲: curveColor =「{Name = aa4643,ARGB =(0,170,70,67)}」 但是當我去在網格中使用它我得到與其他嘗試相同的錯誤 「索引超出範圍。必須是非負數且小於集合的大小。參數名稱:索引「 – RichP

+0

這意味着有時你的Request.QueryString [」color「]爲空,請在調試器中檢查 – SergeyS

+1

SergeyS你的解決方案確實和我的解決方案一樣工作,我非常專注於顏色I沒有看到我設置它的位置,我需要我的線設置顏色後我調用grid.DataBind。沒有在我的網格行...還是很專注於顏色的轉換我忽略了顯而易見的感謝!順便說一句,這也適用:'System.Drawing.ColorConverter oConverter = new System.Drawing.ColorConverter();''Color myColor =(Color)oConverter.ConvertFromString(sColor);' – RichP

相關問題