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.
Related
I have a textbox and i want to write the query in textbox and show the result in datagridview.
if i write something like this Select * From Login in textbox and click on button to show the result in datagridview.
i have tried this code but unable to do it.
SqlConnection con = new SqlConnection(#"Data Source=LAPTOP-A56NKPB9\SQLSERVER;Initial Catalog=DB_EMS;Integrated Security=True");
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("'" + query.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dgv.DataSource = dt;
I know it's a bad idea but i need to complete this task.
I have one drop down list to select student name.when i select a student name in the drop down list, grid view has to show details of selected name.
This is my coding for this but it didn't display anything.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MGLCOMConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT VALUE,VDESC FROM CSOPTFD WHERE OPTFIELD='WONO'AND VALUE LIKE '%" + customerddl.SelectedValue + "%'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
this is my cs code to get the details of selected value.But it didn't any thing.
VALUE is a reserved keyword for T-SQL. Use it with square brackets like [VALUE]
And please use parameterized queries instead. This kind of string concatenations are open for SQL Injection attacks.
SqlCommand cmd = new SqlCommand("SELECT [VALUE], VDESC FROM CSOPTFD WHERE OPTFIELD = 'WONO' AND [VALUE] LIKE '%' + #value + '%'", con);
cmd.Parameters.AddWithValue("#value", customerddl.SelectedValue);
Have you bind Dropdown Correctly,like CustomerId , Text and after that are you calling this code from Selected_Index_Changed Event with PostBack True ?
Try providing the code in a try - catch block. Use the finally block to closed the connection by using con.Close();
Also try closing the connection and then accessing the dataset for values.
SqlConnection con =null;
DataSet ds=null;
try
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["MGLCOMConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT VALUE,VDESC FROM CSOPTFD WHERE OPTFIELD='WONO'AND VALUE LIKE '%" + customerddl.SelectedValue + "%'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
}
catch(SQLException ex)
{
}
finally
{
if(con!=null)
con.Close();
}
GridView1.DataSource = ds;
GridView1.DataBind();
I have created a WebMethod in a WebService that uses stored procedures to find whatever you are searching for.
[WebMethod]
public DataSet getMyData(string search)
{
using (SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("searchingads", conn);
SqlDataAdapter da;
DataSet ds = new DataSet();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#search", search);
da = new SqlDataAdapter(cmd);
da.Fill(ds, "MyData");
conn.Close();
conn.Close();
return ds;
}
I don't know how to call this method from an ASP.NET application. I have a button that, when clicked, needs to call this method and populate a GridView.
I have the following code in my ASP.NET web application (on button click):
WebService1 service = new WebService1();
GridView2.DataSource = service.getMyData(TextBox1.Text);
GridView2.DataBind();
Label1.Text = service.HelloWorld();
The label switches to "hello world" when the button is clicked, but it doesn't give me any table when I do a search.
Thank you in advance for your help.
Please use this
GridView2.DataSource = service.getMyData(TextBox1.Text);
instead of
GridView2.DataSource = service.IskanjeOglasov(TextBox1.Text);
If you have tested your search logic and its returning the data then try by assigning the data table as data source not the data set.
GridView2.DataSource = ((DataSet)service.getMyData(TextBox1.Text)).Tables[0];
GridView2.DataBind();
Here I have removed the check part of dataset. This might work.
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.
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.