Получить GridView Row - PullRequest
       3

Получить GridView Row

3 голосов
/ 19 августа 2011

У меня есть GridView, который я связываю с SqlDataReader на Page_Load. В нем есть столбец с кнопками, и я пытаюсь получить строку при нажатии кнопки со следующим кодом:

int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];

РЕДАКТИРОВАТЬ : вставка страницы .aspx из секций комментариев

 <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" OnRowCommand="GridView1_RowCommand" DataKeyNames="id" GridLines="None"> <AlternatingRowStyle BackColor="White" /> 
    <Columns> 
        <asp:TemplateField> 
             <ItemTemplate> 
                  <asp:Button ID="btnChange" runat="server" Text="Change" CommandName="Test" Visible='<%# Convert.ToBoolean(Eval("Tested")) == true ? true : false %>' /> 
             </ItemTemplate> 
         </asp:TemplateField> 
     </Columns>
</aspx:GridView> 

Я получаю следующую ошибку: 'System.FormatException: входная строка была в неправильном формате.' в строке 'int index = Convert.ToInt32 (e.CommandArgument);'.

Есть идеи?

Ответы [ 4 ]

6 голосов
/ 19 августа 2011

Вам необходимо проверить, какая команда в строке GridView была нажата. Ваша разметка должна соответственно отображаться. Смотрите ЭГС ниже. Получаемый вами e.CommandArgument может не соответствовать вашему нажатию кнопки.

В CodeBehind:

    void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
    {
    // If multiple buttons are used in a GridView control, use the CommandName property to determine which button was clicked.
    if(e.CommandName=="Add")
    {
    // Convert the row index stored in the CommandArgument property to an Integer.
    int index = Convert.ToInt32(e.CommandArgument);

    // Retrieve the row that contains the button clicked by the user from the Rows collection.
    GridViewRow row = CustomersGridView.Rows[index];

    // additional logic...
    }
    // additional logic...
}

В разметке:

Также убедитесь, что вы правильно установили свой атрибут CommandArgument. Пример ниже:

<asp:Button (...) CommandArgument="<%# Container.DataItemIndex %>" />

ИЛИ использовать поле кнопки

<asp:ButtonField ButtonType="button" CommandName="Add" Text="Add" />
1 голос
/ 19 августа 2011

Можете ли вы опубликовать весь код разметки, было бы полезно решить.в соответствии с вашим вопросом в коде gridview aspx вы должны использовать имя команды и команду Argument для кнопки управления, и она должна быть привязана к столбцу db.и использовать команду Row Command для gridview.А также попробуйте использовать ItemTemplate, чтобы поместить элемент управления в сетку.

Нажмите здесь, чтобы ознакомиться с документацией MSDN. Команда строки в GridView

protected void Grid_RowCommand( object sender, GridViewCommandEventArgs e )
{
    int index = Convert.ToInt32( e.CommandArgument );
    your logic .......
}
0 голосов
/ 19 августа 2011

Вы не добавили значение в команду Аргумент. Для вашего события Button на странице .aspx

<asp:Button ID="btnChange" runat="server" Text="Change" CommandName="Test" CommandArgument = 1 Visible='<%# Convert.ToBoolean(Eval("Tested")) == true ? true : false %>' /> 

В коде, стоящем за событием RowCommand

if(e.CommandName == "Test")
{
int index = Convert.ToInt32(e.CommandArgument);
}

Это будет работать только для значения 1. Чтобы сделать его общим, вы можете привязать команду Аргумент к значению, которое вы хотите, используя один из методов привязки, например: CommandArgument ='<%# Eval("ID") %>' (Предполагая, что ID присутствует в GridView)

0 голосов
/ 19 августа 2011

Проверьте этот код

void ContactsGridView_RowCommand(Object sender,GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="Add")
{
  // Convert the row index stored in the CommandArgument
  // property to an Integer.
  int index = Convert.ToInt32(e.CommandArgument);

  // Retrieve the row that contains the button clicked 
  // by the user from the Rows collection.
  GridViewRow row = ContactsGridView.Rows[index];

  // Create a new ListItem object for the contact in the row.     
  ListItem item = new ListItem();
  item.Text = Server.HtmlDecode(row.Cells[2].Text) + " " +
    Server.HtmlDecode(row.Cells[3].Text);

  // If the contact is not already in the ListBox, add the ListItem 
  // object to the Items collection of the ListBox control. 
  if (!ContactsListBox.Items.Contains(item))
  {
    ContactsListBox.Items.Add(item);
  }
 }
}    

Ниже HTML-код для gridview

<asp:gridview id="ContactsGridView" 
          datasourceid="ContactsSource"
          allowpaging="true" 
          autogeneratecolumns="false"
          onrowcommand="ContactsGridView_RowCommand"
          runat="server">

          <columns>
            <asp:buttonfield buttontype="Link" 
              commandname="Add" 
              text="Add"/>
            <asp:boundfield datafield="ContactID" 
              headertext="Contact ID"/>
            <asp:boundfield datafield="FirstName" 
              headertext="First Name"/> 
            <asp:boundfield datafield="LastName" 
              headertext="Last Name"/>
          </columns>

        </asp:gridview>

Проверить ссылку Команды Gridview

Надеюсь, этот ответ поможет вам.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...