Вопрос

i have a gridview that displays query data from 1 table after the user presses a button with a code behind query, this gridview had autogeneratecolumns = false and i added the BoundField DataField header texts myself, for example, the first column in the db had the name "prd_nome" and i changed it to "nome", everything worked as it was supposed to.

now i've created a another table in the db, with a different name and different column names as well, i've also added another button with a code behind query to get data from that table but in order to display the data now the autogeneratecolumns = true, i tested the button and it works, however the header texts are the same as the column names and the ID column is also showing for both queries.

how do i hard code the header texts to what i want and how do i hide the ID column? via labels? via boundfield datafields? via the AS sql operator? if anyone could help me, i would appreciate because i'm a c# novice

here's the current gridview asp code:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true"></asp:GridView>

here's the code of the button that passes a query from the first table:

protected void Button1_Click(object sender, EventArgs e)
{
    DataTable dt = new DataTable();

    SqlConnection connection = new SqlConnection(GetConnectionString());
    connection.Open();
    SqlCommand sqlCmd = new SqlCommand("SELECT * FROM [ERPDQ].[dbo].[prd] WHERE prd_desc LIKE ('torta%')", connection);
    SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

          sqlDa.Fill(dt);
    if (dt.Rows.Count > 0)
    {
        GridView1.DataSource = dt;
        GridView1.DataBind();

    }
    connection.Close();
}

and here's the code from the button that passes a query regarding the second table:

protected void Button6_Click(object sender, EventArgs e)
{
    DataTable dt = new DataTable();

    SqlConnection connection = new SqlConnection(GetConnectionString());
    connection.Open();
    SqlCommand sqlCmd = new SqlCommand("SELECT * FROM [ERPDQ].[dbo].[outra]", connection);
    SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

    sqlDa.Fill(dt);
    if (dt.Rows.Count > 0)
    {
        GridView1.DataSource = dt;
        GridView1.DataBind();

    }
    connection.Close();
}

}

Это было полезно?

Решение 2

When using AutoGenerateColumns=True you can change the header texts of columns by using AS sql operator in your select statement (as you already suggested).

Although in general avoid using AutoGenerateColumns=True, because its inflexible. As you pointed out you get stuck by easy things such as hiding one column.

And here is an example how to hide ID column by using RowDataBound event

protected void rowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        for (int i = 0; i < e.Row.Controls.Count; i++)
        {
            var headerCell = e.Row.Controls[i] as DataControlFieldHeaderCell;
            if (headerCell != null)
            {
                if (headerCell.Text == "name_of_id_column")
                {
                    headerCell.Visible = false;
                    Page.Items["IDCellIndex"] = i;
                    break;
                }
            }
        }   
    }
    else if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Footer)
    {
        int idCellIndex = Convert.ToInt32(Page.Items["IDCellIndex"]);

        e.Row.Controls[idCellIndex].Visible = false;
    }
}

Другие советы

You didn't mention that there is one GridView or there are two GridView.

If there are two GridViews on your page then just add onrowdatabound event for both GridViews.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true"  onrowdatabound="GridView1_RowDataBound"></asp:GridView>

<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="true" onrowdatabound="GridView2_RowDataBound"></asp:GridView>

If there is only 1 GridView then define two Boolean variable (btn1Click,btn2Click)before page load.On button1 click event set btn1Click to ture and btn2Click to false , on button2 click event set btn2Click to true and btn1Click to false and in OnRowDataBound event set columns name according to btn click.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
  //supposing id is the first cell,change the index according to your grid
  // hides the first column
  e.Row.Cells[0].Visible = false; 

  if(btn1Click)
  {
     //to set header text
     if (e.Row.RowType == DataControlRowType.Header)
     {
        e.Row.Cells[1].Text = "Cell Text";
        e.Row.Cells[2].Text = "Cell Text";
     }
  }
  else if(btn2Click)
  {
     //to set header text
     if (e.Row.RowType == DataControlRowType.Header)
     {
        e.Row.Cells[1].Text = "Cell Text";
        e.Row.Cells[2].Text = "Cell Text";
      }
  }
}

Please mark both answers correct if it is working for you.

You can do this on GridView RowDataBound event

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
  //supposing id is the first cell,change the index according to your grid
  // hides the first column
  e.Row.Cells[0].Visible = false; 

  //to set header text
  if (e.Row.RowType == DataControlRowType.Header)
  {
     e.Row.Cells[1].Text = "Cell Text";
     e.Row.Cells[2].Text = "Cell Text";
  }
}

thanks everyone, i'm sure i'll use some of the answers depending on the direction of the project after implementation.

regarding my gridview column header renaming issue, i found out that the AS operator works fine for the current needs, again i appreciate all the help provided

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top