如何通过SQLQuery填充DataGrid

时间:2009-08-06 14:44:12

标签: c# asp.net datagrid

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace Khajohnsubdee.Web.DatagridByQuery
{
    public class DatagridByQuery
    {

        public string strConnect
        {
            set;
            get;
        }

        public DataSet GetDataSource(string sqlQuery, string dataSourceName)
        {
            var dataSet = new DataSet(dataSourceName);
            SqlConnection sc = null;
            try
            {
                var sqlConnection = new SqlConnection(strConnect);
                sqlConnection.Open();
                var sa = new SqlDataAdapter(new SqlCommand(sqlQuery, sc));
                sa.Fill(dataSet);
            } catch
            {
            }
            finally
            {
                if (sc != null) sc.Close();

            }
            return dataSet;
        }
    }
}

这是我的代码

可以使用dataGrid1.Fill(new DatagridByQuery(“Select * From Test”,“test1”));

?感谢

1 个答案:

答案 0 :(得分:0)

尝试使用此...

dataGrid1.DataSource = ds.Tables["yourtablename"].DefaultView; //yourtablename can be set table index
    dataGrid1.DataBind();