簡體   English   中英

asp.net dropDownList選定的值null

[英]asp.net dropDownList selected value null

我正在申請有關文章發表的學校申請。 在dropdownList中,我想顯示數據庫中存在的值作為默認的預選值。 DropdownList從表“ kategorite”隱含“ emertimi”。 當用戶選擇一個值時,它將在表“ artikulli”中保存“ kategoria_id”的id。 這是我的代碼背后

if (e.Item.ItemType == ListItemType.EditItem)
            {
                DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
                SqlConnection con = new SqlConnection(connection);
                string Qry = "select * from kategoria";
                string id = Request.QueryString["id"];
                SqlDataAdapter da = new SqlDataAdapter(Qry, con);
                DataSet ds = new DataSet();
                DataSet ds2 = new DataSet();
                DataSet ds3 = new DataSet();
                con.Open();
                da.Fill(ds);
                string kategoria_id = "select kategoria_id from artikulli where id='" + id + "'";
                SqlDataAdapter dk = new SqlDataAdapter(kategoria_id, con);
                dk.Fill(ds2);
                var kategoria_id_result = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
                string emertimi = "select emertimi from kategoria where id='" + kategoria_id_result + "'";
                SqlDataAdapter de = new SqlDataAdapter(emertimi, con);
                de.Fill(ds3);

                drpdKategoria.DataSource = ds;
                drpdKategoria.DataValueField = "id";
                drpdKategoria.DataTextField = "emertimi";              
                drpdKategoria.DataBind();
                drpdKategoria.SelectedValue = drpdKategoria.Items.FindByText(emertimi).Value;
                con.Close();
                con.Dispose();
                ds.Dispose();
                ds2.Dispose();
                ds3.Dispose();
                da.Dispose();
                dk.Dispose();
                de.Dispose();
            }
        }

但它顯示了此錯誤: 對象引用未設置為object的實例 在這一行: drpdKategoria.SelectedValue = drpdKategoria.Items.FindByText(emertimi).Value;

我猜emertimi包含一個在下拉列表中找不到的值。 因此, FindByText將返回null並且獲取Value將導致此異常。

在嘗試獲取Value之前,請測試結果。

另外,使用using語句代替單獨的Dispose調用。 並且要注意SQL注入的風險:請改用參數。

那是因為找不到您要尋找的商品。 您應該對代碼進行故障排除,並弄清楚在運行時設置了什么emertimi。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM