当前位置:编程学习 > C#/ASP.NET >>

类型化dataset自定义sql语句的问题

刚学.NET,尝试用类型化dataset里自定义sql语句的时候遇到了一点问题,数据库表定义如下:Id(主键),Name,Age
然后我自定义的sql语句如下:

SELECT   Name
FROM      T_Person
WHERE   (Age <6)

查询分析成功,可以产生理想的数据

然后我自定义一个winform,一个button,事件如下

 private void button2_Click(object sender, EventArgs e)
        {
            T_PersonTableAdapter adapter = new T_PersonTableAdapter();
            
            wformApplication_forPractice.Person_DataSet. temTable = adapter.GetDataByAge();

            for (int i = 0; i < temTable.Count; i++)
            {
                wformApplication_forPractice.Person_DataSet.T_PersonRow AgeRow = temTable[i];

                MessageBox.Show(AgeRow.Name);
                
            }
        }

提示出错,我就开始找原因,我发现:必须得select Name,Age 一起才行。如果select name的情况:结果在数据集右键->该GetDataByAge方法行的“预览数据”选项,产生的结果是Id列都为负数,Age列全为空值,请问如何解决这个问题?难道要自己建立一个datatable吗 --------------------编程问答-------------------- 自己建立一个datatable --------------------编程问答--------------------
引用 1 楼 liuqian4243 的回复:
自己建立一个datatable

只能这样吗?vs不会知道帮建立一个tb吗?刚刚学习,不是很懂 --------------------编程问答-------------------- 有人吗???? --------------------编程问答-------------------- 读取数据返回DataTable.

 public static DataTable ReturnDataTable(string cmdtext)
    {
        SqlConnection cn = new SqlConnection();
        cn.ConnectionString = "数据库连接字符串";
        DataTable dt = new DataTable();
        SqlCommand cmd = new SqlCommand();
        cmd = new SqlCommand(cmdtext, cn);
        cmd.CommandType = CommandType.Text; ;
        SqlDataReader dr = null;
        using (dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
        {
            dt.Load(dr);
        }
        return dt;
    }

Name关键字 记得加[Name]
补充:.NET技术 ,  .NET Framework
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,