ASP.NET GridView - Не удается установить цвет строки во время привязки данных? - PullRequest
0 голосов
/ 28 января 2010

Это сводит меня с ума! Это то, что я сотворил с датагридом. Я сейчас использую Gridview, и я не могу понять это.

У меня есть эта сетка:

<asp:GridView AutoGenerateColumns="false" runat="server" ID="gvSelect" CssClass="GridViewStyle"
        GridLines="None" ShowHeader="False" PageSize="20" AllowPaging="True">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Label runat="server" ID="lbldas" Text="blahblah"></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>

А во время RowDataBound я пробовал:

Protected Sub gvSelect_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvSelect.RowCreated
    If e.Row.RowType = DataControlRowType.DataRow Then
        e.Row.Attributes.Add("onMouseOver", "this.style.backgroundColor='lightgrey'")
    End If
End Sub

И это НИКОГДА не устанавливает цвет фона строки .. Я успешно использовал:

gridrow.Cells(0).BackColor = Drawing.Color.Blue

Но делать весь ряд? НЕТУ! и это сводит меня с ума .. У кого-нибудь есть решение для меня?

И просто для удовольствия я поместил это на ЖЕ страницу:

<asp:DataGrid AutoGenerateColumns="false" runat="server" ID="dgSelect" GridLines="None"
        ShowHeader="False" PageSize="20" AllowPaging="True">
        <Columns>
            <asp:TemplateColumn>
                <ItemTemplate>
                    <asp:Label runat="server" ID="lbldas" Text="blahblah"></asp:Label>
                </ItemTemplate>
            </asp:TemplateColumn>
        </Columns>
    </asp:DataGrid>

И в ItemDataBound я положил:

If Not e.Item.ItemType = ListItemType.Header And Not e.Item.ItemType = ListItemType.Footer Then
        e.Item.Attributes.Add("onMouseOver", "this.style.backgroundColor='lightgrey'")
End If

И все работает как положено .. ТАК Что я делаю не так с Gridview?

** ОБНОВЛЕНИЕ ************************

Я решил опубликовать полученный HTML-код, чтобы показать, что любые стили не влияют на это.

Вот html вида сетки:

<div class="AspNet-GridView" id="gvSelect"> 
<table cellpadding="0" cellspacing="0" summary=""> 
    <tbody> 
        <tr> 
            <td> 
                <span id="gvSelect_ctl02_lbldas">blahblah</span> 
            </td> 
        </tr> 
    </tbody> 
</table> 
 </div>

А вот итоговый HTML-код Datagrid:

<table cellspacing="0" border="0" id="dgSelect" style="border-collapse:collapse;"> 
<tr onMouseOver="this.style.backgroundColor='lightgrey'"> 
    <td> 
        <span id="dgSelect_ctl03_lbldas">blahblah</span> 
            </td> 
</tr>
 </table> 

Смотри .. главное отличие - тег. Это никогда не будет установлено в gridview ... и я не знаю почему ... Я проследил это ... и код запускается ..: S

Ответы [ 4 ]

0 голосов
/ 01 сентября 2010

Используете ли вы CSSFriendly Control Adapters для ваших GridViews? Они могут не отображать добавленные вами атрибуты.

0 голосов
/ 29 января 2010

Это на самом деле должно быть сделано во время RowCreatedEvent. Просто протестировал следующий код, и он прекрасно работал, чтобы выделить / отменить выделение строки при наведении курсора.

Private Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowCreated
    If e.Row.RowType = DataControlRowType.DataRow Then
        e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#ccaaaa';")
        e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#ffffff';")
    End If
End Sub

EDIT: добавление вывода html (ПРИМЕЧАНИЕ: работает как в VB, так и в C # с RowCreated - одинаковый вывод)

<div>
  <table cellspacing="0" rules="all" border="1" id="GridView1" style="border-collapse:collapse;">
    <tr>
      <th scope="col">ST_CD</th><th scope="col">ST_CD_ALPHA</th><th scope="col">ST_DESC</th>
    </tr><tr onmouseover="this.style.backgroundColor='#ccaaaa';" onmouseout="this.style.backgroundColor='#ffffff';">
      <td>04</td><td>CA</td><td>CALIFORNIA                    </td>
    </tr><tr onmouseover="this.style.backgroundColor='#ccaaaa';" onmouseout="this.style.backgroundColor='#ffffff';">
      <td>34</td><td>OH</td><td>OHIO                          </td>
    </tr><tr onmouseover="this.style.backgroundColor='#ccaaaa';" onmouseout="this.style.backgroundColor='#ffffff';">
      <td>41</td><td>TN</td><td>TENNESSEE                     </td>
    </tr><tr onmouseover="this.style.backgroundColor='#ccaaaa';" onmouseout="this.style.backgroundColor='#ffffff';">
      <td>42</td><td>TX</td><td>TEXAS                         </td>
    </tr><tr onmouseover="this.style.backgroundColor='#ccaaaa';" onmouseout="this.style.backgroundColor='#ffffff';">
      <td>45</td><td>VA</td><td>VIRGINIA                      </td>
    </tr><tr onmouseover="this.style.backgroundColor='#ccaaaa';" onmouseout="this.style.backgroundColor='#ffffff';">
      <td>46</td><td>WA</td><td>WASHINGTON                    </td>
    </tr><tr onmouseover="this.style.backgroundColor='#ccaaaa';" onmouseout="this.style.backgroundColor='#ffffff';">
      <td>49</td><td>WY</td><td>WYOMING                       </td>
    </tr><tr onmouseover="this.style.backgroundColor='#ccaaaa';" onmouseout="this.style.backgroundColor='#ffffff';">
      <td>14</td><td>IA</td><td>IOWA                          </td>
    </tr><tr onmouseover="this.style.backgroundColor='#ccaaaa';" onmouseout="this.style.backgroundColor='#ffffff';">
      <td>24</td><td>MO</td><td>MISSOURI                      </td>
    </tr><tr onmouseover="this.style.backgroundColor='#ccaaaa';" onmouseout="this.style.backgroundColor='#ffffff';">
      <td>40</td><td>SD</td><td>SOUTH DAKOTA                  </td>
    </tr><tr onmouseover="this.style.backgroundColor='#ccaaaa';" onmouseout="this.style.backgroundColor='#ffffff';">
      <td>43</td><td>UT</td><td>UTAH                          </td>
    </tr><tr onmouseover="this.style.backgroundColor='#ccaaaa';" onmouseout="this.style.backgroundColor='#ffffff';">
      <td>44</td><td>VT</td><td>VERMONT                       </td>
    </tr><tr onmouseover="this.style.backgroundColor='#ccaaaa';" onmouseout="this.style.backgroundColor='#ffffff';">
      <td>47</td><td>WV</td><td>WEST VIRGINIA                 </td>
    </tr><tr onmouseover="this.style.backgroundColor='#ccaaaa';" onmouseout="this.style.backgroundColor='#ffffff';">
      <td>48</td><td>WI</td><td>WISCONSIN                     </td>
    </tr><tr onmouseover="this.style.backgroundColor='#ccaaaa';" onmouseout="this.style.backgroundColor='#ffffff';">
      <td>54</td><td>AK</td><td>ALASKA                        </td>
    </tr>
  </table>
</div>

РЕДАКТИРОВАТЬ: Вот HTML-сторона, которая у меня есть. Я держал это простым. Возможно, на вашей стороне HTML у вас есть конфигурация css, которая мешает.

<div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        DataSourceID="SqlDataSource1">
        <Columns>
            <asp:BoundField DataField="ST_CD" HeaderText="ST_CD" SortExpression="ST_CD" />
            <asp:BoundField DataField="ST_CD_ALPHA" HeaderText="ST_CD_ALPHA" 
                SortExpression="ST_CD_ALPHA" />
            <asp:BoundField DataField="ST_DESC" HeaderText="ST_DESC" 
                SortExpression="ST_DESC" />
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:WebTestConnectionString %>" 

        SelectCommand="SELECT [ST_CD], [ST_CD_ALPHA], [ST_DESC] FROM [STATE_VALUES] WHERE ([ST_CD] LIKE '%' + @ST_CD + '%')">
        <SelectParameters>
            <asp:Parameter DefaultValue="4" Name="ST_CD" Type="String" />
        </SelectParameters>
    </asp:SqlDataSource>

</div>
0 голосов
/ 15 июня 2010

Эта проблема возникает в IE6. Я решил это с помощью установки имен CssClass всех ячеек в строке gridview. Вот код:

private void grdvw_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
       e.Row.Attributes.Add("onmouseover", "rowHighlight(this,'lightOn');"); 
       e.Row.Attributes.Add("onmouseout", "rowHighlight(this,'');");
    }
}

function rowHighlight(obj, nameOfTheClass) 
{
   cells = obj.getElementsByTagName("td");
   for (var i = 0; i < cells.length; i++) 
   {
       cells[i].className = nameOfTheClass;
   }
}
0 голосов
/ 29 января 2010

Я сделал это так:

Protected Sub gvwCompounds_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        e.Row.CssClass = "rowstyle"
    End If
End Sub

и в example.css:

.rowstyle
{
    background-color:#e5e5e5;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...