0

我正在研究 asp.net 和 c#。

我有一个从 sql 数据库填充的 gridview。我有下拉列表和文本框控件。

在 RowDataBound 事件中,我为控件分配了值:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Control ctrlgridEstacion = e.Row.FindControl("grid1");
            if (ctrlgridEstacion != null)
            {
                DropDownList dd = ctrlgridEstacion as DropDownList;
                SqlDataReader dr;
                SqlCommand cmd;
                cmd = new SqlCommand();
                cmd.Connection = sqlConn;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "sp_load";
                sqlConn.Open();
                dr = cmd.ExecuteReader();
                DataTable dt = new DataTable();
                dt.Load(dr);
                dd.DataSource = dt;
                dd.DataValueField = "code";
                dd.DataTextField = "code";
                dd.DataBind();
                DataRowView rowView = (DataRowView)e.Row.DataItem;
                string tempDate = rowView["code"].ToString();
                dd.SelectedIndex = dd.Items.IndexOf(dd.Items.FindByText(tempDate));
                sqlConn.Close();
            }

Control gridPrefijo = e.Row.FindControl("grid2");
            if (gridPrefijo != null)
            {
                TextBox dd = gridPrefijo as TextBox;
                DataTable dt = new DataTable();
                sqlConn.Open();
                SqlCommand cmd;
                cmd = new SqlCommand();
                cmd.Connection = sqlConn;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "sp_load";
                SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);
                sqlDa.Fill(dt);
                int startIndex;

                if (c1 < 1)
                {
                    int RC = dt.Rows.Count;
                    int PS = GridView1.PageSize;
                    int PN = GridView1.PageIndex + 1;
                    startIndex = (PN - 1) * PS;
                    int endIndex = Math.Min(RC - 1, startIndex + PS - 1);
                    dri = startIndex;
                }

                if (dt.Rows.Count > 0)
                {
                    dd.Text = dt.Rows[dri ]["name"].ToString();
                    c1++;
                }
                sqlConn.Close();
            }
}

}

问题是我有 15 个控件,因此将它们添加到 RowDatabound 事件是很多代码。如何使代码更小?

谢谢..

4

0 回答 0