2014-10-07 2 views
1
private void fill() 
{ 
    adptr = new OleDbDataAdapter(@"SELECT * FROM LibraryInfo WHERE First_Name='"+LoginName+"'", cn);  
    //LoginName is a string variable for displaying users info after the login   
    ds.Clear(); 
    adptr.Fill(ds); 
    dataGridView1.DataSource = ""; 
    dataGridView1.DataSource = ds.Tables[0]; 
} 

После обновления базы данных GridView не отображает данные.GridView не отображает данные

+1

удалить эту строку dataGridView1.DataSource = ""; и включите более подробную информацию, чтобы мы могли помочь вам .... –

+7

Мое имя для входа ... 'MrSQLInjection '); DROP TABLE LibraryInfo; - 'P.s. не используйте мое имя;) – Reniuz

+1

Единственный фрагмент, отсутствующий в OP, - 'dataGridView1.DataBind();' –

ответ

1

Взято из этого msdn статья о DataBind Недвижимость.


ASP Пример


void Page_Load(Object sender, EventArgs e) 
    { 

    // This example uses Microsoft SQL Server and connects 
    // to the Northwind sample database. The data source needs 
    // to be bound to the GridView control only when the 
    // page is first loaded. Thereafter, the values are 
    // stored in view state.      
    if(!IsPostBack) 
    { 
     // Declare the query string. 
     String queryString = 
     "Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"; 

     // Run the query and bind the resulting DataSet 
     // to the GridView control. 
     DataSet ds = GetData(queryString); 
     if (ds.Tables.Count > 0) 
     { 
     AuthorsGridView.DataSource = ds; 
     AuthorsGridView.DataBind(); 
     } 
     else 
     { 
     Message.Text = "Unable to connect to the database."; 
     } 

    }  

    } 

    DataSet GetData(String queryString) 
    { 

    // Retrieve the connection string stored in the Web.config file. 
    String connectionString = ConfigurationManager.ConnectionStrings["NorthWindConnectionString"].ConnectionString;  

    DataSet ds = new DataSet(); 

    try 
    { 
     // Connect to the database and run the query. 
     SqlConnection connection = new SqlConnection(connectionString);   
     SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection); 

     // Fill the DataSet. 
     adapter.Fill(ds); 

    } 
    catch(Exception ex) 
    { 

     // The connection failed. Display an error message. 
     Message.Text = "Unable to connect to the database."; 

    } 

    return ds; 

    } 

Этот фрагмент кода показывает, как (а) связать свой набор данных в GridView, назначив его с помощью метода DataBind.

Сайт также говорит:

Используйте метод DataBind() для связывания данных из источника данных в GridView контроля. Этот метод разрешает все выражения привязки данных в активном шаблоне элемента управления.

РЕШЕНИЕ

Я хотел бы сослаться на линию, говоря:

AuthorsGridView.DataBind(); 

, который фактически связывает данные с контролем.

SIDE ПРИМЕЧАНИЕ

Чтобы защитить себя от SQLI, вы должны прочитать на SQL Parameters, а не прямой конкатенации.


Winform Пример


Учебник был найден: here

//create the connection string 
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\myDatabase.mdb"; 

//create the database query 
string query = "SELECT * FROM MyTable"; 

//create an OleDbDataAdapter to execute the query 
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString); 

//create a command builder 
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter); 

//create a DataTable to hold the query results 
DataTable dTable = new DataTable(); 

//fill the DataTable 
dAdapter.Fill(dTable); 

также:

//the DataGridView 
DataGridView dgView = new DataGridView(); 

//BindingSource to sync DataTable and DataGridView 
BindingSource bSource = new BindingSource(); 

//set the BindingSource DataSource 
bSource.DataSource = dTable; 

//set the DataGridView DataSource 
dgView.DataSource = bSource; 
+0

Что вы пытаетесь сделать с этим ответом? – Tushar

+1

show OP Как привязать сетку, как указано в вопросе. Я также могу спросить то же, что вы прокомментировали? – jbutler483

+0

Это красиво написано, но оно подходит только для asp.net. Вопрос OPs о winforms, о котором он указывал (к сожалению!) До конца ... – DatRid

0

Использование отсутствуют для вызова метода DataBind here.Use следующий код:

DataAdapter adapter=new DataAdapter(SqlCommand,SqlConn); 
DataTable tbl=new Datatable(); 
adapter.Fill(tbl); 
GridView1.DataSource=tbl; 
GridView1.DataBind();//This line is missing in your code 

попробуйте использовать этот формат?

+0

, есть ошибка в части GridView1. DataBind(); кажется, что он не может пересоздать .DataBind(); – tokazaki

Смежные вопросы