如何在繫結資料的DropDownList下拉選單中第一行新增空白項?

xiaosong2008發表於2014-04-15

    問:

    protected void GridView_DataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            SqlConnection con = null;
            con = new SqlConnection("Max Pool Size = 512;Server=  ; User ID=  ;password=j  ; Initial Catalog=xx系統");
            con.Open();
            string sqlstr = "select name from table1";
            SqlDataAdapter da = new SqlDataAdapter(sqlstr, con);
            DataSet ds = new DataSet();
            da.Fill(ds, "table1");
            DropDownList ddl = (DropDownList)e.Row.FindControl("DDLname");           
                  DataView dv = new DataView();
            dv = ds.Tables["table1"].DefaultView;
            ddl.DataSourceID = null;
            ddl.DataSource = dv;
            ddl.DataTextField = "name";
            ddl.DataValueField = "name";
               ddl.SelectedIndex = 0;
            ddl.DataBind();
        }
    }
問題:我已經把資料庫中table1表的name列繫結到DDLname下拉選單中,如何在下拉選單中第一行新增一個空白項 ?


答:

    DataView dv = new DataView();
            dv = ds.Tables["table1"].DefaultView;
改成:
            DataTable dt = ds.Tables["table1"];
            DataRow dr=dt.NewRow();
            dr["name"]="--請選擇--";//這裡為空白項的內容
            dt.Rows.InsertAt(dr, 0);
            DataView dv = dt.DefaultView;



相關文章