且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Commandtext属性尚未初始化

更新时间:2022-11-16 07:37:11

这是不好的做法使用

It is bad practice to use
if ()
else if ()



即使您认为您的变量永远不会有意外价值,也没有最终的其他声明。



将会发生什么如果你的定义语句没有达到,那么程序会在最后一个if之后运行到语句。



要么添加else语句处理这个未定义的情况或更改为带有默认语句的switch语句。




without a final else statement even if you think your variable will never have an unexpected value.

What will happen if your defined statements are not met is that the program runs through to the statement after the last else if.

Either add an else statement that takes care of this undefined case or change to a switch statement with a default statement.

if (radio.SelectedValue == "0")
{
    sql = ...
}
else if (radio.SelectedValue == "1")
{
    sql = ...
}
else
{
    throw new Exception(string.Format("Selected value is undefined: {0}.", radio.SelectedValue));
}






or

switch (radio.SelectedValue)
{
    case 1: sql = ...; break;
    case 2: sql = ...; break;
    default: throw new Exception(string.Format("Selected value is undefined: {0}.", radio.SelectedValue));
}


确保 SqlCommandText 不为空/空执行之前SqlCommand

如果您选择的值大于1,则SqlCommandText值将为空,这将导致异常。



使用前验证

Ensure that the SqlCommandText is not null/Empty before executing an SqlCommand
If you selected value is greater than 1, the SqlCommandText value will be empty which results in Exception.

Validate it before usage
if (sql != "")  // Validate for non empty
            {

                SqlCommand cmd = new SqlCommand(sql, conn);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);

                ddlcity.DataSource = ds;

                ddlcity.DataTextField = "cityname";
                ddlcity.DataValueField = "cityid";
                ddlcity.DataBind();
                ddlcity.Items.Insert(0, new ListItem("--Select--", "0"));
            }