Pergunta

I want to rename column names in GridView in multiple pages. So far, I can change one at a time. Here's my code:

protected void Button1_Click(object sender, EventArgs e)
{

    for (int i = 0; i < GridView1.Columns.Count; i++)
    {
        if (GridView1.Columns[i].HeaderText == TextBox1.Text)
        {
            GridView1.Columns[i].HeaderText = TextBox2.Text;
        }

    }


}

In the design view I have two textboxes and a button. When I click the button it gets textbox1 and renames that column that I typed in textbox2.

What I am trying to do: I have multiple pages and I want to change their column HeaderText. I don't want to add these buttons and textboxes to each page. Is there any way to call this function only once and change the HeaderTexts in all pages?

Thank you in advance.

Foi útil?

Solução

I solved it by sending the column name to database and i get the new headertext from database in Page_Load. I know that this is not the best solution, it's slow due to its connecting to database everytime page loads. Better than nothing. :)

Database part:

 try
    {
        con.Open();
        string[] _col = {  }; // Enter here the column names
        for (int i = 0; i < _col.Length; i++)
        {
            if (_col[i] == TextBox1.Text)
            {
                SqlCommand ins = new SqlCommand("insert into Kolon_Ismi_Degistirme (ind, newHeaderName) values (@ind, @newHeaderName)", con);
                ins.Parameters.AddWithValue("@ind", i);
                ins.Parameters.AddWithValue("@newHeaderName", TextBox2.Text);
                ins.ExecuteNonQuery();
            }
        }
    }
    catch (Exception)
    {
        throw;
    }
    finally
    {
        con.Close();
    }

page_load part

 try
    {
        //Get new column name using database                        
        con.Open();
        SqlCommand sel = new SqlCommand("select ind, newHeaderName from Kolon_Ismi_Degistirme", con);
        reader = sel.ExecuteReader();
        while (reader.Read())
        {
            GridView1.Columns[(int)reader["ind"] + 2].HeaderText = (string)reader["newHeaderName"];
        }                
    }
    catch (global::System.Exception)
    {
        throw;
    }
    finally
    {
        reader.Close();
        con.Close();
    }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top