asp.net GridView RowDataBound较小的代码

时间:2012-09-27 20:17:07

标签: asp.net

我在asp.net和c#上工作。

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

在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事件中需要很多代码。 如何缩小代码?

谢谢..

0 个答案:

没有答案