简体   繁体   English

下拉列表的空值不适用于所选文本C#?

[英]Drop Down list null value not working for selected text c#?

Basically I have a drop down list which is populated with text and values depending on a selected index of a radio button list. 基本上,我有一个下拉列表,其中填充了文本和值,具体取决于单选按钮列表的选定索引。 The code is as follows: 代码如下:

protected void RBLGender_SelectedIndexChanged(object sender, EventArgs e)
    {
        DDLTrous.Items.Clear();
        DDLShoes.Items.Clear();
        if (RBLGender.SelectedValue.Equals("Male"))
        {

            String[] MaleTrouserText = {"[N/A]", "28\"", "30\"", "32\"", "34\"", "36\"", "38\"", "40\"", "42\"", "44\"", "48\""};
            String[] MaleTrouserValue = { null, "28\"", "30\"", "32\"", "34\"", "36\"", "38\"", "40\"", "42\"", "44\"", "48\"" };
            String[] MaleShoeText = { "[N/A]", "38M", "39M", "40M", "41M", "42M", "43M", "44M", "45M", "46M", "47M" };
            String[] MaleShoeValue = { null, "38M", "39M", "40M", "41M", "42M", "43M", "44M", "45M", "46M", "47M" };
            for (int i = 0; i < MaleTrouserText.Length; i++)
            {
                ListItem MaleList = new ListItem(MaleTrouserText[i], MaleTrouserValue[i]);
                DDLTrous.Items.Add(MaleList);

            }
            for (int i = 0; i < MaleShoeText.Length; i++)
            {
                ListItem MaleShoeList = new ListItem(MaleShoeText[i], MaleShoeValue[i]);
                DDLShoes.Items.Add(MaleShoeList);

            }

        }

            else if (RBLGender.SelectedValue.Equals("Female"))`

When the text '[N/A]' is selected I want the value NULL to be inserted into the database. 当选择文本'[N / A]'时,我希望将NULL值插入数据库。 At present when '[N/A]' is selected the value entered into the database is [N/A] does anyone know why? 目前,当选择“ [N / A]”时,输入数据库的值为[N / A],有人知道为什么吗?

This is my DB insertion code: 这是我的数据库插入代码:

protected void UpdateWorkWear()
    {



        try
        {

            string connectionString = Common.GetConnectionString("w34to4tmConnectionString");

            SqlConnection conn = new SqlConnection(connectionString);

            StringBuilder sbSQL = new StringBuilder();


            string str = DDLSurname.SelectedValue;

            if (str.Contains("'"))
            {
                str = str.Replace("'", " ");

            }

            sbSQL.Append("IF EXISTS (select * from TO4_WORKWEAR_DISTRIBUTION where EmpID = @EmpID)");
            sbSQL.Append(" UPDATE TO4_WORKWEAR_DISTRIBUTION SET ");
            sbSQL.Append("costCentre = coalesce(@Cost_Centre, CostCentre), EmployeeType = coalesce(@EmployeeType, EmployeeType), Initials = coalesce(@Initials, Initials), Surname = coalesce(@Surname, Surname), ");
            sbSQL.Append("IssueQuarter = coalesce(@IssueQuarter, IssueQuarter), TrouserSize = coalesce(@Trouser_S, TrouserSize), TrouserLength = coalesce(@Trouser_L, TrouserLength), ");
            sbSQL.Append("PoloSize = coalesce(@Polo_S, PoloSize),  SweatSize = coalesce(@Sweat_S,SweatSize), ShortSize = coalesce(@Short_S, ShortSize), ShoeSize = coalesce(@Shoe_S, ShoeSize) WHERE EmpID = @EmpID ");
            sbSQL.Append(" else INSERT INTO TO4_WORKWEAR_DISTRIBUTION (EmpID,CostCentre, EmployeeType, Initials, Surname, IssueQuarter, TrouserSize, TrouserLength, PoloSize, SweatSize, ShortSize, ShoeSize) ");
            sbSQL.Append("VALUES (@EmpID, @Cost_Centre, @EmployeeType, @Initials, @Surname, @IssueQuarter, @Trouser_S, @Trouser_L, @Polo_S, @Sweat_S, @Short_S, @Shoe_S)");




            sbSQL.Replace("@EmpID", "'" + DDLEmpID.SelectedValue + "'");
            sbSQL.Replace("@Cost_Centre", "'" + DDLCostCentre.SelectedValue + "'");
            sbSQL.Replace("@EmployeeType", "'" + RBLAssociate.SelectedValue + "'");
            sbSQL.Replace("@Initials", "'" + DDLInitials.SelectedValue + "'");
            sbSQL.Replace("@Surname", "'" + str + "'");
            sbSQL.Replace("@Trouser_S", "'" + DDLTrous.SelectedValue + "'");
            sbSQL.Replace("@Trouser_L", "'" + DDLTrouserLnh.SelectedValue + "'");
            sbSQL.Replace("@Trouser_Q", "'" + DDLTrouserQty.SelectedValue + "'");
            sbSQL.Replace("@Polo_S", "'" + DDLPolo.SelectedValue + "'");
            sbSQL.Replace("@Polo_Q", "'" + DDLPoloQty.SelectedValue + "'");
            sbSQL.Replace("@Sweat_S", "'" + DDLSweat.SelectedValue + "'");
            sbSQL.Replace("@Sweat_Q", "'" + DDLSweatQty.SelectedValue + "'");
            sbSQL.Replace("@Shoe_S", "'" + DDLShoes.SelectedValue + "'");
            sbSQL.Replace("@Short_S", "'" + DDLShor.SelectedValue + "'");
            sbSQL.Replace("@InputDate", "'" + System.DateTime.Now.Date.ToString("MM/dd/yyyy") + "'");
            sbSQL.Replace("@IssueQuarter", "'" + RBLQuarter.SelectedValue + "'");

            SqlCommand cmd = new SqlCommand(sbSQL.ToString(), conn);
            cmd.CommandType = CommandType.Text;

            conn.Open();

            int result = cmd.ExecuteNonQuery(); //execute the SQL command on the database   
            LiteralControl lit = new LiteralControl();
            lit.Text = String.Format("Data Uploaded Successfully.");

Thanks for all your help guys. 感谢您的帮助。 I have decided to insert blank strings "" into the datbase instead of null now as it makes my life slightly easier when i run reports from it. 我决定现在将空白字符串“”插入datbase而不是null中,因为当我从它运行报表时,这使我的生活变得更加轻松。

The problem is that if a ListItem has its value set to null, it will use the Text property as the value. 问题是,如果ListItem的值设置为null,它将使用Text属性作为值。 For example this code: 例如这段代码:

ListItem l = new ListItem("Cats", null);

string s = l.Value;

The value of s is "Cats". s的值为“猫”。

The solution is not to store null, but store an empty string, or -1, or something similar, and then check for this in your code. 解决方案不是存储null,而是存储一个空字符串或-1或类似的东西,然后在代码中进行检查。

AC# null is not the same as a database NULL. AC#null与数据库NULL不同。

In your insertion code you probably need to pick up that the value is "N/A"/null and then insert a DBNull instead. 在您的插入代码中,您可能需要选择值为“ N / A” / null,然后插入一个DBNull。 What does your DB insertion code look like? 您的数据库插入代码是什么样的?

From my interpretation of C# ListItems, if the Value is not defined, then when you look up the Value, you'll get the Text. 根据我对C#ListItems的解释,如果未定义Value,则在查找Value时将获得Text。 It's probably a simple if (Value == null) return Text; if (Value == null) return Text;可能很简单if (Value == null) return Text; check, so naturally if you deliberately set the Value as null, it will then return the Text instead of your null value. 检查,因此自然地,如果您故意将Value设置为null,它将返回Text而不是您的null值。

Another way to look at it is that you're calling the new ListItem(string, string) constructor, but passing a null value for the second argument. 另一种查看方法是,您正在调用new ListItem(string, string)构造函数,但为第二个参数传递了一个null值。 This basically calls new ListItem(string) , which likewise sets the Value to the Text. 这基本上是调用new ListItem(string) ,它同样将Value设置为Text。 Mayhaps not literally, but the end result is the same. 也许不是字面上的意思,但最终结果是相同的。

EDIT 编辑

I did some testing of this in a simple situation. 我在一个简单的情况下对此进行了一些测试。 If you initialize a ListItem object with a null value for its Value, then both ListItem.Value and DropDownList.SelectedValue (when pointing at that list item) will get you the same value as your Text. 如果使用值的null值初始化ListItem对象,则ListItem.Value和DropDownList.SelectedValue(指向该列表项时)都将获得与Text相同的值。 As such, it can be inferred that initializing a ListItem with a null Value sets the Value to the same as the Text. 这样,可以推断出,使用null值初始化ListItem会将Value设置为与Text相同。 Even setting it later to null via ListItem.Value = null; 甚至以后将其设置null经由ListItem.Value = null; will still set it to the Text. 仍将其设置为文本。

You will have to set the Value to some value, and instead of directly inputting the SelectedValue, run a check for if the SelectedValue equals this preset value. 您将必须将Value设置为某个值,而不是直接输入SelectedValue,而是检查SelectedValue是否等于此预设值。 I personally use _|NULL|_ . 我个人使用_|NULL|_

Code Snippet 代码段

ListItem li;
li = new ListItem("Test", null);
Console.WriteLine(li.Value.ToString());
li.Value = null;
Console.WriteLine(li.Value.ToString());
DropDownList ddl = new DropDownList();
ddl.Items.Add(li);
ddl.SelectedIndex = 0;
Console.WriteLine(ddl.SelectedValue);
Console.ReadLine();

Output 产量

Test
Test
Test

使用DBNull.Value而不是null。

您可以简单地做到这一点:

sbSQL.Replace("@Trouser_S", (DDLTrous.SelectedValue == "[N/A]" ? "NULL" : "'" + DDLTrous.SelectedValue + "'"));

You need to show how you are pulling the data off the drop down list and putting it into the db. 您需要显示如何从下拉列表中提取数据并将其放入数据库中。 Use the SelectedItem property to get the ListItem ( you may have to cast it ) and then explicitly call the ListItem.Value for the db insert/update. 使用SelectedItem属性获取ListItem(您可能必须强制转换),然后显式调用数据库插入/更新的ListItem.Value。

edit... doing for code 编辑...做代码

instead of 代替

 sbSQL.Replace("@Trouser_S", "'" + DDLTrous.SelectedValue + "'");

do

ItemList il = (ItemList)DDLTrous.SelectedItem;
string s = il.Value;
if ( s != null )
  s = "'" + s + "'";
else
  s = "null";

sbSQL.Replace("@Trouser_S", s);

you might also try replacing null with "null" in the value. 您也可以尝试将值中的null替换为“ null”。 But the key thing is that you cannot have the "'" + x + "'" around the null value otherwise it goes in as a string. 但是关键是,您不能在空值附近使用“'” + x +“'”,否则它将作为字符串进入。

edit again.. 再次编辑..

if ItemList.Value cannot be null, then have the value be "null" and change the if statement. 如果ItemList.Value不能为null,则其值为“ null”并更改if语句。

ItemList il = (ItemList)DDLTrous.SelectedItem;
string s = il.Value;
if ( s != "null" )
  s = "'" + s + "'";

sbSQL.Replace("@Trouser_S", s);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM