获取data()编译错误 [英] Get data() compilation error
本文介绍了获取data()编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Text;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.DataSource = GetData();
DropDownList1.DataValueField = "Branch";
DropDownList1.DataTextField = "Branch";
DropDownList1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection Cn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=F:\AAAAAAAAAAA\FINGERPRINT\APP_DATA\QUESTIONS.MDF;Integrated Security=True;"))
{
using (SqlCommand Cmd = new SqlCommand("select * from questions where Branch= @Branch"))
{
Cn.Open();
Cmd.Parameters.AddWithValue("@Branch", int.Parse(DropDownList1.SelectedValue));
SqlDataReader Dr = Cmd.ExecuteReader();
if (Dr.HasRows)
{
GridView1.DataSource = Dr;
GridView1.DataBind();
}
Dr.Close();
Cn.Close();
}
}
}
DataTable GetData()
{
DataTable dt = new DataTable();
SqlConnection Con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=F:\AAAAAAAAAAA\FINGERPRINT\APP_DATA\QUESTIONS.MDF;Integrated Security=True;");
{
SqlCommand Cmd = new SqlCommand("SELECT * FROM questions ");
Con.Open();
SqlDataAdapter adpt = new SqlDataAdapter(Cmd);
adpt.Fill(dt);
}
}
}
我尝试过:
i尝试添加受保护但在数据表中得到相同的错误getdata()
What I have tried:
i have try add protected but get same error in data table getdata()
推荐答案
在GetData()方法中,您正在创建数据表但从不返回它,因此我假设您的编译错误是并非所有路径都返回值。它应该如下所示:
In GetData() method you are creating the data table but never returning it so I assume your compilation error is "not all paths are returning a value". It should look like this:
DataTable GetData()
{
DataTable dt = new DataTable();
using(SqlConnection Con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=F:\AAAAAAAAAAA\FINGERPRINT\APP_DATA\QUESTIONS.MDF;Integrated Security=True;"))
using(SqlCommand Cmd = new SqlCommand("SELECT * FROM questions ", Con))
{
Con.Open();
SqlDataAdapter adpt = new SqlDataAdapter(Cmd);
adpt.Fill(dt);
}
return dt; // <-- this is what you were missing
}
请注意我添加了使用语句,因为SqlConnectin和SqlCommand都实现了IDisposable。
Please note I added using statements as both SqlConnectin and SqlCommand implement IDisposable.
您将GetData声明为返回DataTable,但该方法不返回任何内容。
在方法结尾处添加以下行:
You declared GetData as returning a DataTable, but the method does not return anything.
Add this line at the end of the method:
return dt;
BTW:不要对连接字符串进行硬编码:从配置文件中读取它们!
BTW: don't hardcode connection strings: read them from a configuration file!
这篇关于获取data()编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文