本文介绍了C#中的Invalidoperationexception错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
InvalidOperationException error in C#
我的代码:
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace Expense_System
{
public partial class Transactions : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from Expense_Type");
DropDownListexpensetype.DataSource = cmd.ExecuteReader();
DropDownListexpensetype.DataTextField = "Expense_Type";
DropDownListexpensetype.DataValueField = "Expense_Type";
DropDownListexpensetype.DataBind();
}
protected void BtncreateExpense_Click(object sender, EventArgs e)
{
}
}
}
我的尝试:
谷歌搜索它但没有得到正确的解决方案
What I have tried:
Googled it but not getting proper solution
推荐答案
protected void Page_Load(object sender, EventArgs e){
if(!IsPostback){
BindList();
}
}
private void BindList(){
String strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using(SqlConnection con = new SqlConnection(strConnString)){
using(SqlCommand cmd = new SqlCommand("select * from Expense_Type", con)){
con.Open();
DropDownListexpensetype.DataSource = cmd.ExecuteReader();
DropDownListexpensetype.DataTextField = "Expense_Type";
DropDownListexpensetype.DataValueField = "Expense_Type";
DropDownListexpensetype.DataBind();
}
}
}
注意:我注意到你已经分配了字段 Expense_Type
适用于文本
和值
。只需确保 DataValueField
包含唯一值,以避免在从列表中选择/预选值时出现意外行为。
Note: I've noticed that you've assigned the field Expense_Type
for both Text
and Value
. Just make sure that the DataValueField
contain unique values to avoid unexpected behavior when selecting/pre-selecting values from the list.
SqlCommand cmd = new SqlCommand("select * from Expense_Type", con);
SqlCommand cmd = new SqlCommand("select * from Expense_Type", con);
这篇关于C#中的Invalidoperationexception错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!