在基于下拉列表选择显示网格视图中选择初始值时出错 [英] Error on selecting initial value in Displaying gridview based on drop down list selection

查看:67
本文介绍了在基于下拉列表选择显示网格视图中选择初始值时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户选择初始值时请选择我得到一个例外。

转换nvarchar值时转换失败'请选择'到数据类型int。

初始值必须以编程方式添加

如何修复错误,下面是我的代码,除非选择初始值,否则该代码正常工作。

When user selects the initial value Please Select I get an exception which is.
Conversion failed when converting the nvarchar value 'Please Select' to data type int.
The Initial value has to be added programmatically
How do I fix the error,below is my code which works correctly except if the initial value is selected.

protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack)
        {
        string cn = ConfigurationManager.ConnectionStrings["connectivity"].ConnectionString;
        using(SqlConnection connection=new SqlConnection(cn))
        {
           
            SqlCommand command = new SqlCommand("select * from Employees",connection);
            connection.Open();
            //command.Parameters.AddWithValue("@id",DropDownList1.SelectedValue);
            SqlDataReader dr = command.ExecuteReader();
            DropDownList1.DataTextField = "name";
            DropDownList1.DataValueField = "id";
            DropDownList1.DataSource = dr;
            DropDownList1.DataBind();
            ListItem li = new ListItem("Please Select");
            DropDownList1.Items.Insert(0, li); 
        }
    }
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string cn = ConfigurationManager.ConnectionStrings["connectivity"].ConnectionString;
        using (SqlConnection connection = new SqlConnection(cn))
        {
            SqlCommand command = new SqlCommand("select * from Employees where id=@id", connection);
            connection.Open();
            command.Parameters.AddWithValue("@id",DropDownList1.SelectedValue);
            SqlDataReader dr = command.ExecuteReader();
            GridView1.DataSource = dr;
            GridView1.DataBind();

        }
    }

推荐答案

绑定你的下拉菜单



Bind your dropdown like

SqlCommand command = new SqlCommand("select * from Employees",connection);
connection.Open();
SqlDataAdapter da=new SqlDataAdapter(command);
DataSet ds=new DataSet();
da.fill(ds);
DropDownList1.DataSource =ds; 
DropDownList1.DataBind(); 





in if(!Page.IsPostBack)以及 DropDownList1_SelectedIndexChanged



并在定义本身中定义下拉列表的选定值。无需在此代码中进行。



问候.. :)



in if(!Page.IsPostBack) as well as DropDownList1_SelectedIndexChanged

and define selected value of dropdown in definition itself. No need to make it in this code.

Regards.. :)


这篇关于在基于下拉列表选择显示网格视图中选择初始值时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆