Evening all.
I have the following code that I need looking into - basically I'm clutching at straws here. I have a gridview that I would like to assign tooltips to.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
f开发者_开发知识库oreach (TableCell cell in e.Row.Cells)
{
foreach (System.Web.UI.Control ctl in cell.Controls)
{
if (ctl.GetType().ToString().Contains("DataControlLinkButton"))
{
Dictionary<String, String> headerTooltips = new Dictionary<String, String>();
headerTooltips["Product ID"] = "A unique product ID";
headerTooltips["Product Description"] = "Description of product";
String headerText = cell.Text;
cell.Attributes.Add("title", headerTooltips[headerText]);
}
}
}
}
}
Essentially what I am trying to achieve is a tool tip that appears by each column heading (i.e. Product ID and Product Description.)
However, when I use the above code, I receive the following error message "The given key was not present in the dictionary." This appears on the
cell.Attributes.Add("title", headerTooltips[headerText]);
line.
Can someone point out the error in my ways? Thank you for any help or suggestions.
The error is caused because you haven't added an entry to your dictionary that corresponds to the value of cell.Text. The only keys your dictionary contains is 'Product ID' and 'Product Description' so unless you have cells that actually contain this text it will always fail. You could do this:
if (headerTooltips.ContainsKey(headerText))
{
cell.Attributes.Add("title", headerTooltips[headerText]);
}
Which gets you beyond the exception but don't think it does what you are trying to accomplish.
Edit:
Do you just want the cell.Text to show up as the tooltip? If yes then do this:
// This is only replacing the foreach part, the rest of your code is still valid
foreach (System.Web.UI.Control ctl in cell.Controls)
{
if (ctl.GetType().ToString().Contains("DataControlLinkButton"))
{
cell.Attributes.Add("title", cell.Text);
}
}
精彩评论