0

我想在多个页面中重命名 GridView 中的列名。到目前为止,我可以一次更换一个。这是我的代码:

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;
        }

    }


}

在设计视图中,我有两个文本框和一个按钮。当我单击按钮时,它会获取 textbox1 并重命名我在 textbox2 中键入的那一列。

我正在尝试做的事情:我有多个页面,我想更改他们的列 HeaderText。我不想将这些按钮和文本框添加到每个页面。有没有办法只调用一次这个函数并更改所有页面中的 HeaderTexts?

先感谢您。

4

1 回答 1

0

我通过将列名发送到数据库来解决它,并从 Page_Load 中的数据库中获取新的标题文本。我知道这不是最好的解决方案,由于每次加载页面时都会连接到数据库,因此速度很慢。有总比没有好。:)

数据库部分:

 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 部分

 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();
    }
于 2012-05-05T13:30:08.250 回答