I try to bind database data to the gridview in c# and asp.net. But I couldn't see the datas in the gridview.Rows are added to the gridview but they are empty. When I run that query in SQLServer, it gives the correct result.I didn't add or change any code to the asp part.Should I? I couldn't find where is the problem :( please help..
myConnection = WebConfigurationManager.ConnectionStrings["KutuphaneConnectionString"].ConnectionString;
connect = new SqlConnection(myConnection);
command = new SqlCommand();
connect.Open();
command.Connection = connect;
string komut = "SELECT K.ad,K.yazar,K.baskiNo,O.sonTeslimTarihi FROM OduncIslemleri O,Kitap K WHERE O.kullaniciId=" + Session["id"] + " AND O.kitapId = K.id;";
try
{
SqlCommand sqlCommand = new SqlCommand();
sqlCommand = connect.CreateCommand();
sqlCommand.CommandText = komut;
SqlDataAdapter sda = new SqlDataAdapter(sqlCommand.CommandText, connect);
SqlCommandBuilder scb = new SqlCommandBuilder(sda);
//Create a DataTable to hold the query results.
DataTable dTable = new DataTable();
//Fill the DataTable.
sda.Fill(dTable);
GridView1.DataSource = dTable;
GridView1.DataBind();
}
catch (SqlException)
{
//Console.WriteLine(e.StackTrace);
}
reader.Close();
connect.Close();
Here is the correct answer :
myConnection = WebConfigurationManager.ConnectionStrings["KutuphaneConnectionString"].ConnectionString;
connect = new SqlConnection(myConnection);
string sorgu = "select K.ad,K.yazar,K.baskiNo,O.sonTeslimTarihi from Kitap K, OduncIslemleri O where O.kitapId = K.id and O.kullaniciId = "+ Session["id"];
SqlDataAdapter sadp = new SqlDataAdapter(sorgu, connect);
DataSet ds = new DataSet();
sadp.Fill(ds);
this.GridView1.DataSource = ds.Tables[0];
this.GridView1.DataBind();
connect.Close();
I also used template fields in Gridview. Also autogeneratedFields should be true. I hope this helps to the people who have the same problem
watch for another event triggered after the bind that could be clearing the rows
Try creating a DataSet and populate that using Fill instead. I've never seen Fill used on a DataTable - and can't find that particular overload on MSDN. My suspicion is, though, that such an overload would not modify the existing schema of the DataTable (which, since it's only just been created prior to use in your example, would mean that it has no columns).
I think you have to use a BindingSource Control, you set the DataSource of it to the DataTable, and then set the GridView's DataSource to the BindingSource.
Related
as stated in the title, I would appreciate some help with populating comboboxes with different columns of the same table
I don't have the actual source codes with me but I was able to populate one combobox with something like
SqlDataTable dt = new SqlDataTable();
SqlCommand comm = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
da.Fill(dt);
myCMB.DataSource = dt;
myCMB.DisplayMember = "display";
myCMB.ValueMember = "value;
but I have 5 comboboxes, and I didn't want to repeat the same blocks of code 5 times just for that. so I looked around and found some answers, including changing datasource to bindingsource, like so:
myCMB.DataSource = new BindingSource(da, "Column_Name");
but doing so would populate the combobox with each letter of the first item of the specified column (ie. if the first item in "Column_Name" is ABCD, my combobox options would be A,B,C,D)
So, I tried looking for more answers but I can't find any. is there a more efficient way of populating my comboboxes or do I really have to repeat essentially the same lines of code for each of them? if anyone can help, it would be greatly appreciated.
Use a copy of the datatable:
SqlDataTable dt = new SqlDataTable();
SqlCommand comm = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
da.Fill(dt);
myCMB.DataSource = dt.Copy();
myCMB.DisplayMember = "display";
myCMB.ValueMember = "value;
Try this:
DataTable dt = new DataTable();
dt.Columns.Add("Value");
dt.Columns.Add("Display");
string query = #"SELECT ID AS ID, Description AS CODE FROM [Tender] ORDER BY ID";
SqlDataReader sqlReader = new SqlCommand(query, DB.SQLConnection).ExecuteReader();
while (sqlReader.Read())
{
if (!string.IsNullOrEmpty(sqlReader["CODE"].ToString()))
dt.Rows.Add(sqlReader["ID"].ToString(), sqlReader["CODE"].ToString());
}
cbPayment1.DisplayMember = "display";
cbPayment1.ValueMember = "value";
cbPayment1.DataSource = dt;
I am using SQL to fill my datagridview. I am doing that this way:
string cn = ConfigurationManager.ConnectionStrings["Scratchpad"].ConnectionString;
SqlConnection myConnection = new SqlConnection(cn);
string sql = "some text here";
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, myConnection);
DataSet ds = new DataSet();
myConnection.Open();
dataadapter.Fill(ds, "Authors_table");
myConnection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";
Now it deletes the old datagridview and paste the selection. But I want just to add the data to the column right of the existing data.
Thanks in advance
This requirement sounds like it could be met with a SQL Inner Join in the query you're using in your SqlDataAdapter. If you were able to join your two data sources together on matching keys, you could simply pull the data down once. But I'm going to assume there's some reason why that won't work for you.
You can in fact do what you want with a DataSet, but you'll need to take a few more steps:
string sql = "The first query"
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, myConnection);
DataSet ds = new DataSet();
myConnection.Open();
dataadapter.Fill(ds, "Authors_table");
myConnection.Close();
// I don't know what your primary key is, but you need to have one.
// I am assuming it's called "author_id".
DataColumn authorIdColumn = ds.Tables["Authors_table"].Columns["author_id"];
ds.Tables["Authors_table"].PrimaryKey = new[] { authorIdColumn };
// Get your second set of data
sql = "My second query, which also has the same primary key, but has more columns"
dataadapter = new SqlDataAdapter(sql, myConnection);
dataadapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
DataSet ds2 = ds.Clone();
myConnection.Open();
dataadapter.Fill(ds2, "Authors_table");
myConnection.Close();
// Now we use the DataSet.Merge method, which is very powerful.
ds.Merge(ds2, false, MissingSchemaAction.AddWithKey);
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";
You may have to experiment with that a lot: this is just the outline. Without knowing your data and what you do up to this point, it's hard to know what settings or methods you might also need to call.
Try this. I ran multiple queries in one go
SqlDataAdapter adapter = new SqlDataAdapter(
"SELECT * FROM Customers; SELECT * FROM Orders", connection);
adapter.TableMappings.Add("Table", "Customer");
adapter.TableMappings.Add("Table1", "Order");
adapter.Fill(ds);
I have a gridview that I'm binding from my database within my onload method.
As shown:
if (!IsPostBack)
{
SqlConnection sqlcon = new SqlConnection(connstring);
SqlCommand sqlcmd = new SqlCommand("select * from Coffees ORDER BY coffeeName ASC", sqlcon);
SqlDataAdapter adp = new SqlDataAdapter(sqlcmd);
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
I'm allowing my users to filter the gridview on their search term. The issue I'm following at the moment is that when i change pages, the filter is lost.
I have read I need to rebind the filter eachtime and this is where im getting stuck.
Here is my filter:
private void setGrid(string searchTerm)
{
if (IsPostBack)
{
string item = DropDownList2.SelectedValue;
SqlConnection sqlcon = new SqlConnection(connstring);
SqlCommand sqlcmdd = new SqlCommand("SELECT * FROM Coffees WHERE " + searchTerm + " = '" + item + "'", sqlcon);
SqlDataAdapter adpp = new SqlDataAdapter(sqlcmdd);
DataSet dss = new DataSet();
adpp.Fill(dss);
GridView1.DataSource = dss.Tables[0];
GridView1.DataBind();
}
}
As shown above I have an if statement that handles the Postback. Postback is something I still have to try and get my head around but I believe what this is doing is reloading the grid if its a Postback. I have tried to change this so if it is a Postback it is not affected but this just ignores the filter all together.
Hopefully someone can give me an idea where I'm going wrong. And How I can apply the filter acrodd all of y pages.
I saved the search term as a viewstate variable, then applied in my page index changing method an if to check if it was null or not. Then I either re-bound the grid on the searchterm, or a standard bind to show all the results.
I'm trying to take information from my SQL server and load it into a datagridview based on paramaters selected by the user. The example I post at the end of this question worked in an earlier function in the program, but now it isn't. This leads me to believe that the issue lies in the line that actually outputs the data to the DGV. Any thoughts on why it's not filling up the DGV? I've included two examples, neither of which is working. For some reason, they're just not inputting any information into the DGV, even though I know from debugging that they are indeed pulling the information from the server successfully.
SqlConnection DBConnection = new SqlConnection(ConnectionString);
//Opens the connection
DBConnection.Open();
//Creates a string to hold the query
string query = "SELECT * FROM PRD WHERE PRD_NUM LIKE '" +OutputBeforeIncrement + "%'";
//Creates an SQLCommand object to hold the data returned by the query
SqlCommand queryCommand = new SqlCommand(query, DBConnection);
//Uses the aforementioned SQLCommand to create an SQLDataReader object
SqlDataReader queryCommandReader = queryCommand.ExecuteReader();
//Creates a DataTable to hold the data
DataTable dataTable = new DataTable();
//This part actually loads the data from the query into the table
dataTable.Load(queryCommandReader);
dgvOutput.DataSource = dataTable;
The other example:
using (SqlDataAdapter newDA = new SqlDataAdapter(query, DBConnection))
{
DataTable Table = new DataTable();
newDA.Fill(Table);
dgvOutput.DataSource = Table;
}
You might try this or something similar:
SqlDataAdapter myDataAdapter;
SqlCommandBuilder myCommandBuilder;
SqlCommand mySqlCommand = new SqlCommand(myQuery, MySQLConnection);
//I think this is the default command type, and thus can be omitted
mySqlCommand.CommandType = CommandType.Text;
myDataAdapter = new SqlDataAdapter(mySqlCommand);
//Automates your insert/update/delete
myCommandBuilder = new SqlCommandBuilder(myDataAdapter);
myDataAdapter.Fill(myDataTable);
dgvOutput.DataSource = myDataTable.DefaultView;
I am pulling data from a sql server and putting it into a grid using c#. When the data displays on the grid, it is showing up as the guid rather than the actual name. How do I get the name to show and not the uniqe identifier. Any ideas? Thanks.
Here is some of the code:
public InventoryWindow()
{
InitializeComponent();
if (dgDataView != null)
{
SqlConnection con = new SqlConnection(connString);
SqlDataAdapter adpt = new SqlDataAdapter("select * from Item", con);
DataSet ds = new DataSet();
adpt.Fill(ds, "Item");
dgDataView.DataContext = ds;
//dgDataView.DataMember = "Item";
showdata();
}
}
private void showdata()
{
String connString = "server=server;database=database;user=user;password=password";
SqlConnection con = new SqlConnection(connString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from Item", con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dgDataView.DataContext = dt;
con.Close();
}
You are using select * from Item and therefore returning all columns. You could just specify the columns you want in the Grid, in the order you want them. The grid by default has autocolumn generation on.
You can also specify the columns you want and what fields they map to using the columns DataMember values.
I figured this out, I just wrote my own query to display certain columns instead of automatically showing all of them.