如何在自动生成的GridView中获取标头名称

如何在自动生成的GridView中获取标头名称

本文介绍了如何在自动生成的GridView中获取标头名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在自动生成的 Button 单击事件中的 GridView 中获取标题名称.标题列始终不能相同..

How to get the header name in an autogenerated GridView in a Button click event.header column must not be same..all the time..

因此,根据列标题,我们必须进一步处理.请帮助找到列标题.

So depending upon the column header we have to process further. Please help to find the column header.

我们正在通过以下代码找到行索引

We are finding the rowindex by below code

var rowIndex = ((GridViewRow)((Control)sender).NamingContainer).RowIndex;

像这样.那么,当在 GridView 内单击链接按钮时,如何找到 GridView 的列索引?

like this. So how to find the column index of a GridView when a link button is clicked inside the GridView?

'

string dt1 = txtFromDate.Text;
     string d1, d5 = "", d3 = "", d4 = "", date, d6, service_Date;
    if (dt1 != "")
    {
        d1 = dt1;
        if (d1.Contains("."))
        {
            string[] word = d1.Split('.');
            d5 = word[0];
            d3 = word[1];
            d4 = word[2];
        }
        else if (d1.Contains("-"))
        {
            string[] word = d1.Split('-');
            d5 = word[0];
            d3 = word[1];
            d4 = word[2];
        }
        else if (d1.Contains("/"))
        {
            string[] word = d1.Split('/');
            d5 = word[0];
            d3 = word[1];
            d4 = word[2];
        }

        date = d4 + "/" + d3 + "/" + d5;
        service_Date = d5 + "-" + d3 + "-" + d4;
    }
    else
    {
        date = "";
        service_Date = "";
    }

    string dt2 = txtToDate.Text;
    string t1, t5 = "", t3 = "", t4 = "", d2, t6, serv;
    if (dt1 != "")
    {
        t1 = dt2;
        if (t1.Contains("."))
        {
            string[] word = t1.Split('.');
            t5 = word[0];
            t3 = word[1];
            t4 = word[2];
        }
        else if (t1.Contains("-"))
        {
            string[] word = t1.Split('-');
            t5 = word[0];
            t3 = word[1];
            t4 = word[2];
        }
        else if (t1.Contains("/"))
        {
            string[] word = t1.Split('/');
            t5 = word[0];
            t3 = word[1];
            t4 = word[2];
        }


        d2 = t4 + "/" + t3 + "/" + t5;
        serv = t5 + "-" + t3 + "-" + t4;
        //d5 = d3 + "/" + d6 + "/" + d4 ;
    }
    else
    {
        d2 = "";
        serv = "";
    }
    dttest.Columns.Add("MACHINENAME_DATE");
    ArrayList Array_machine = new ArrayList();
    using (con = new SqlConnection(con_str))
    {
        con.Open();
        string qry;

        qry = "select distinct mname from tb_reqmach  where fromdate>='" + date + "' and todate<='" + d2 + "' and mcfact='" + drpfact.Text + "' group by mname  ";
        cmd = new SqlCommand(qry, con);
        dr = cmd.ExecuteReader();

        while (dr.Read())
        {
            Array_machine.Add(dr["mname"].ToString().Trim());
            //dttest.Rows.Add();
            dttest.Rows.Add(dr["mname"].ToString().Trim());
        }

        con.Close();
    }

    ArrayList Array_L = new ArrayList();
    DateTime startDate = Convert.ToDateTime(date);
    Array_L.Add(startDate.ToString("MM-dd-yyyy"));
    dttest.Columns.Add(startDate.ToShortDateString());
    DateTime endDate = Convert.ToDateTime(d2);
    while (startDate < endDate)
    {

        startDate = startDate.AddDays(1);
        Array_L.Add(startDate.ToString("MM-dd-yyyy"));
        dttest.Columns.Add(startDate.ToShortDateString());
    }


    DataTable dt = new DataTable();
    int m = 0;

    for (int j = 0; j < Array_L.Count; j++)
    {
        int avail = 0;
        int planned = 0;
        int req = 0;

        for (int d = 0; d < Array_machine.Count; d++)
        {
            //dttest.Columns.Add();
            //  dttest.Columns.Add();
            //  xlworksheet.Cells[4 + d, 1] = Array_machine[d];
            // dttest.Rows.Add();
            string machine_name = Array_machine[d].ToString();
            string Date = Array_L[j].ToString();
            // xlworksheet.Cells[3, m + 2] = Date;



            //DataColumn[] keyColumns = new DataColumn[1];
            //keyColumns[0] = dttest.Columns["MACHINENAME/DATE"];
            //dttest.PrimaryKey = keyColumns;
            //if (dttest.Rows.Contains(machine_name))
            //{
            //}
            //else
            //{
            //dttest.Rows.Add(machine_name);
            //}
            //   dttest.Rows[d][1] = Array_machine[d];

            // [xlworksheet].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
            //    xlworksheet.Range["A3", m + 2].Interior.Color = System.Drawing.ColorTranslator.FromHtml("#99CCFF");
            //  dt.Columns.Add(machine_name);
            using (con = new SqlConnection(con_str))
            {

                con.Open();
                string qry1;

                //qry = "select distinct mname from tb_reqmach where mcfact='" + drpfact.Text + "' group by mname ";
                qry1 = "select count(mcdesp) as mcdesp from machine where mcdesp='" + Array_machine[d].ToString().Trim() + "' and mcfact='" + drpfact.Text + "' ";
                cmd = new SqlCommand(qry1, con);
                dr = cmd.ExecuteReader();
                if (dr.Read())
                {
                    // xlworksheet.Cells[dtcount + 1, m + 7] = dr["mcdesp"].ToString().Trim();
                    avail = Convert.ToInt32(dr["mcdesp"].ToString().Trim());
                }
                con.Close();
                con.Open();
                string qry;

                qry = "SELECT sum(rmachine) as mname FROM tb_reqmach WHERE '" + Array_L[j].ToString() + "' BETWEEN fromdate AND todate and mname='" + Array_machine[d].ToString().Trim() + "' and mcfact='" + drpfact.Text + "'";
                cmd = new SqlCommand(qry, con);
                dr = cmd.ExecuteReader();

                if (dr.Read())
                {
                    //  dttest.Rows.Add();
                    //xlworksheet.Columns[i].ColumnWidth = 18;
                    //  xlworksheet.Cells[d + 4, 2 + m] = dr["mname"].ToString().Trim();
                    dttest.Rows[d][j + 1] = dr["mname"].ToString().Trim();
                    if (dr["mname"].ToString().Trim() != "")
                    {
                        planned = Convert.ToInt32(dr["mname"].ToString().Trim());
                        req = avail - planned;
                        int rows = d + 4;
                        int cols = 2 + m;
                        // string rowA = FindResA(rows);
                        // string colB = FindResB(cols);
                        if (req < 0)
                        {
                            // xlworksheet.Range[colB + rows, colB + rows].Interior.Color = System.Drawing.ColorTranslator.FromHtml("#ff0000");
                        }
                        else
                        {
                            //  xlworksheet.Range[colB + rows, colB + rows].Interior.Color = System.Drawing.ColorTranslator.FromHtml("#008000");
                        }
                    }

                    //  dttest.Rows[d][m+1] = dr["mname"].ToString().Trim();
                    // xlworksheet.Columns.AutoFit();
                    // gvtest.HeaderRow.Cells(d).Text = dr["mname"].ToString().Trim();
                    //dt.Rows.Add();
                    // dt.Rows[d][machine_name] = dr["mname"].ToString().Trim();
                }

                con.Close();

            }

        }
        m++;
        //    gvtest.DataSource = dt;
        //  gvtest.DataBind();
        //ID = (i + 1).ToString();
        //  string machine_name = Array_machine[j].ToString();
        // xlworksheet.Cells[4 + i, 1] = ID;
        //  xlworksheet.Cells[4 + i, 2] = machine_name;
        // xlworksheet.Cells[3, m + 2] = machine_name;
        //
    }

    Session["dttest"] = dttest;
    GridView4.DataSource = dttest;
    GridView4.DataBind();






    for (int j = 0; j < Array_L.Count; j++)
    {
        int avail = 0;
        int planned = 0;
        int req = 0;

        for (int d = 0; d < Array_machine.Count; d++)
        {
            //dttest.Columns.Add();
            //  dttest.Columns.Add();
            //  xlworksheet.Cells[4 + d, 1] = Array_machine[d];
            // dttest.Rows.Add();
            string machine_name = Array_machine[d].ToString();
            string Date = Array_L[j].ToString();
            // xlworksheet.Cells[3, m + 2] = Date;



            //DataColumn[] keyColumns = new DataColumn[1];
            //keyColumns[0] = dttest.Columns["MACHINENAME/DATE"];
            //dttest.PrimaryKey = keyColumns;
            //if (dttest.Rows.Contains(machine_name))
            //{
            //}
            //else
            //{
            //dttest.Rows.Add(machine_name);
            //}
            //   dttest.Rows[d][1] = Array_machine[d];

            // [xlworksheet].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
            //    xlworksheet.Range["A3", m + 2].Interior.Color = System.Drawing.ColorTranslator.FromHtml("#99CCFF");
            //  dt.Columns.Add(machine_name);
            using (con = new SqlConnection(con_str))
            {

                con.Open();
                string qry1;

                //qry = "select distinct mname from tb_reqmach where mcfact='" + drpfact.Text + "' group by mname ";
                qry1 = "select count(mcdesp) as mcdesp from machine where mcdesp='" + Array_machine[d].ToString().Trim() + "' and mcfact='" + drpfact.Text + "' ";
                cmd = new SqlCommand(qry1, con);
                dr = cmd.ExecuteReader();
                if (dr.Read())
                {
                    // xlworksheet.Cells[dtcount + 1, m + 7] = dr["mcdesp"].ToString().Trim();
                    avail = Convert.ToInt32(dr["mcdesp"].ToString().Trim());
                }
                con.Close();
                con.Open();
                string qry;

                qry = "SELECT sum(rmachine) as mname FROM tb_reqmach WHERE '" + Array_L[j].ToString() + "' BETWEEN fromdate AND todate and mname='" + Array_machine[d].ToString().Trim() + "' and mcfact='" + drpfact.Text + "'";
                cmd = new SqlCommand(qry, con);
                dr = cmd.ExecuteReader();

                if (dr.Read())
                {
                    //  dttest.Rows.Add();
                    //xlworksheet.Columns[i].ColumnWidth = 18;
                    //  xlworksheet.Cells[d + 4, 2 + m] = dr["mname"].ToString().Trim();
                    // dttest.Rows[d][j + 1] = dr["mname"].ToString().Trim();
                    if (dr["mname"].ToString().Trim() != "")
                    {
                        planned = Convert.ToInt32(dr["mname"].ToString().Trim());
                        req = avail - planned;
                        int rows = d + 4;
                        int cols = 2 + m;
                        // string rowA = FindResA(rows);
                        // string colB = FindResB(cols);
                        if (req < 0)
                        {
                            GridView4.Rows[d].Cells[j + 1].BackColor = Color.Red;
                        }
                        else
                        {

                        }
                    }

                }

                con.Close();

            }

        }
        m++;

    }


    foreach (GridViewRow gr in GridView4.Rows)
    {
        // LinkButton hp = new LinkButton();
        for (int k = 1; k < dttest.Columns.Count; k++)
        {
            LinkButton hp = new LinkButton();
            if (gr.Cells[k].Text != "")
            {
                hp.Text = gr.Cells[k].Text;
                //defsur_Click(sender, e);
                //GridViewRow gvr = e.Row;
                //var rowIndex = ((GridViewRow)((Control)sender).NamingContainer).RowIndex;
                //Label username = (Label)GridView3.Rows[rowIndex].FindControl("machinename");
                //mcname = username.Text;
                // hp.Attributes.Add("onclick", "Gridview4_linkclick");
                hp.Click += new EventHandler(Gridview4_linkclick);
                // hp.NavigateUrl = "~/Default.aspx?name=" + hp.Text;
                gr.Cells[k].Controls.Add(hp);
            }
        }

    }
    GridView4.Columns[0].Visible = false;'

推荐答案

您可以使用此代码段.它将循环单击所单击按钮所在行中的所有单元格,并尝试找到正确的列.

You can use this snippet. It loops all the cells in the row the clicked button is in and tries to find the correct column.

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    //get the control that fired the method
    Control control = e.CommandSource as Control;

    //get the row containing the control
    GridViewRow gvr = control.NamingContainer as GridViewRow;

    //get the row number
    int rowNumber = gvr.RowIndex;

    //declare the column variable
    int columnNumber = -1;

    //loop all the columns in the gridview
    for (int i = 0; i < GridView1.Columns.Count; i++)
    {
        //try to find the button that was clicked in each individual cell
        Button button = GridView1.Rows[rowNumber].Cells[i].FindControl(control.ID) as Button;

        //if the button is found set the column number
        if (button != null)
        {
            columnNumber = i;
        }
    }

    //get the column name
    Label1.Text = GridView1.HeaderRow.Cells[columnNumber].Text;
}

GridView示例

GridView example

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" OnRowCommand="GridView1_RowCommand">
    <Columns>
        <asp:TemplateField HeaderText="Header 1">
            <ItemTemplate>
                <asp:Button ID="Button1" runat="server" Text="Button" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

这篇关于如何在自动生成的GridView中获取标头名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 06:21