Refreshing Gridview After Button Click - c#

on my asp.net project, how can i refresh my gridview immediately after clicking my button.
my button has update codes.here is the codes;
protected void Button3_Click(object sender, EventArgs e)
{
string strSQL = "UPDATE [bilgiler3] SET [HAM_FM] = ISNULL(MON,0)+ISNULL(TUE,0)+ISNULL(WED,0)+ISNULL(THU,0)+ISNULL(FRI,0)+ISNULL(SAT,0)+ISNULL(SUN,0) WHERE [DATE] BETWEEN #DATE1 AND #DATE2 AND WORK_TYPE='OUT'";
string connStr = WebConfigurationManager.ConnectionStrings["asgdb01ConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandText = strSQL;
comm.CommandType = CommandType.Text;
comm.Parameters.AddWithValue("#DATE1", Convert.ToDateTime(TextBox1.Text));
comm.Parameters.AddWithValue("#DATE2", Convert.ToDateTime(TextBox2.Text));
try
{
conn.Open();
int i = comm.ExecuteNonQuery();
conn.Close();
if (i > 0)
{
Response.Write(" SUCCESS ");
}
else
{
Response.Write(" ERROR ! ");
}
}
catch (SqlException ex)
{
Response.Write(ex.ToString());
}
}
}
}
you maybe gonna say "you need to bind the data of your gridview" but i couldnt understand the method.
can you help me about it ?
thank you very much.

I would do the following:
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter();
SqlConnection sc = new SqlConnection("you connection string here Security=True");
private void loadData()
{
try
{
ds.Clear();
SqlCommand sCmd= new SqlCommand("Load your database", sc);
sda.SelectCommand = sCmd;
sda.Fill(ds, "sCmd");
datagrid.DataSource = ds.Tables["sCmd"];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.ExitThread();
}
}
something for c# beginners Youtube

Add this code on your button click
SqlConnection con = new SqlConnection("Connection string from web config");
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter("select * from EmployeeTable", con);
con.Open();
sda.Fill(ds ,"Data");
gridview1.datasource=ds.tables[0];
gridview1.DataBind();

private SqlConnection con;
private SqlConnectionStringBuilder str;
private void Form8_Load(object sender, EventArgs e)
{
loadData();
}
private void loadData()
{
str = new SqlConnectionStringBuilder();
str.Provider = "";
str.DataSource = #"source.accdb";
con = new SqlConnection(str.ConnectionString);
dataGridView1.DataSource = fillTable("Select* from yourTable");
}
private DataTable fillTable(string sql)
{
DataTable datatable = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(sql, con))
{
da.Fill(datatable);
}
return datatable;
}
then If you want to refresh the table you put the loaddata(); in the event button_Click hope this help,

DataBind your control on success.
if (i > 0)
{
yourGridView.DataSource=YourDataSource;
yourGridView.DataBind();
Response.Write(" SUCCESS ");
}

Related

How to use DataGridView to see database record?

This is my first ADO.NET project, I need to finish my professor casestudy. I want to create a windows form and put a Textbox to input the caseid and use a button find. When I click the find button, I can see the caseid and assigned solutions based on a SQL Select statement. I find an example and use a SqlDataReader, but when I click find, I cannot see the result on the form.
So, could you give me some suggestion how to design a datagridview here ?
Thanks
Sophia
I implement my code like this:
private void Find_Click(object sender, EventArgs e)
{
string querystring = "SELECT * FROM AssignedSolution WHERE CASEID = #caseid";
SqlCommand Vcom = new SqlCommand(querystring, vcon1);
Vcom.Parameters.AddWithValue("#caseid", txtCASEID.Text);
SqlDataReader rdr = null;
try
{
Vcom.Connection = vcon1;
Vcom.ExecuteNonQuery();
rdr = Vcom.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0]);
}
Vcom.Dispose();
}
catch (Exception ex)
{
MessageBox.Show("error.occured" + ex.Message);
}
finally
{
vcon1.Close();
vcon1.Dispose();
}
}
DataGridViewRowCollection.Add Method?
while (rdr.Read())
{
Console.WriteLine(rdr[0]);
dataGridView1.Rows.Add(rdr[0], rdr[1], rdr[2], rdr[3], ..);
}
you can try something like this (of course if your project is WinForm):
private void Find_Click(object sender, EventArgs e)
{
DataTable table = null;
using (SqlConnection vcon1 = new SqlConnection(this.connectionString))
{
try
{
vcon1.Open();
SqlCommand Vcom = vcon1.CreateCommand();
Vcom.CommandText = "SELECT * FROM AssignedSolution WHERE CASEID = #caseid";
Vcom.Parameters.Add(new SqlParameter("#caseid", txtCASEID.Text));
using (SqlDataAdapter adapter = new SqlDataAdapter(Vcom))
{
table = new DataTable();
adapter.Fill(table);
}
}
catch (Exception ex)
{
//Handle your exception;
}
}
dataGridView1.DataSource = table;
}
How to from the beginning.
Add in HTML page:
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>
And in Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillGridView();
}
}
public void FillGridView()
{
try
{
string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
string selectSQL = "SELECT * FROM YourTableName";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "YourTableName");
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch
{
Response.Write("<script> alert('Connection error') </script>");
}
}
Also you need in web.config file to store your connection string
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="ConnectionStringName" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI"/>
</connectionStrings>
Hi Sophia,
You Can Use SqlDataAdapter or SqlDataReader with DataTable to show data in Datagridview Like
// Use SqlDataAdapter
private void Find_Click(object sender, EventArgs e)
{
string ConStr = Convert.ToString(ConfigurationManager.AppSettings["strConn"]);
SqlConnection vcon1 = new SqlConnection(ConStr);
vcon1.Open();
string querystring = "SELECT * FROM AssignedSolution WHERE CaseId = #caseid";
SqlCommand Vcom = new SqlCommand(querystring, vcon1);
Vcom.Parameters.AddWithValue("#caseid",Convert.ToInt32(txtCASEID.Text));
try
{
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(Vcom);
da.Fill(dt);
dataGridView1.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show("error.occured" + ex.Message);
}
finally
{
Vcom.Dispose();
vcon1.Close();
vcon1.Dispose();
}
}
// Use SqlDataReader
private void button1_Click(object sender, EventArgs e)
{
string ConStr = Convert.ToString(ConfigurationManager.AppSettings["strConn"]);
SqlConnection vcon1 = new SqlConnection(ConStr);
vcon1.Open();
string querystring = "SELECT * FROM AssignedSolution WHERE CaseId = #caseid";
SqlCommand Vcom = new SqlCommand(querystring, vcon1);
Vcom.Parameters.AddWithValue("#caseid", Convert.ToInt32(txtCASEID.Text));
SqlDataReader dr = null;
try
{
DataTable dt = new DataTable();
dr = Vcom.ExecuteReader();
dt.Load(dr);
dataGridView1.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show("error.occured" + ex.Message);
}
finally
{
dr.Close();
Vcom.Dispose();
vcon1.Close();
vcon1.Dispose();
}
}

What is the way to populate a dropdownlist from a database in asp.net by using classes?

I am trying to populate a dropdownlist from sql server by using classes as shown below. The code breaks down when it comes to bind the data into the dropdown list. It gives an error on giving the dropdownlist the dataValueField and datatTextField.
HTML... a.aspx
<asp:DropDownList ID="NationalityDropDownList" runat="server" >
</asp:DropDownList>
C#... a.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Classes.Nationality PossibleNationality = new Classes.Nationality();
if (!Page.IsPostBack)
{
DataTable dataTable = PossibleNationality.getNationality();
NationalityDropDownList.DataSource = dataTable;
NationalityDropDownList.DataValueField = "ID";
NationalityDropDownList.DataTextField = "Nationality";
NationalityDropDownList.DataBind();
}
}
Nationality.cs
public class Nationality
{
public DataTable getNationality()
{
SqlConnection conn;
SqlCommand comm;
string connectionString = ConfigurationManager.ConnectionStrings["InformationConnection"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("spGetAllUsers", conn);
comm.CommandType = CommandType.StoredProcedure;
DataTable dataTable;
try
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
dataTable = new DataTable();
da.Fill(dataTable);
}
finally
{
conn.Close();
}
return dataTable;
}
}
SQL procedure....
ALTER PROCEDURE [dbo].[spGetNationalities]
AS
BEGIN
select * from Nationality;
END
This line of code in your getNationalitymethod...
comm = new SqlCommand("spGetAllUsers", conn);
...should be this instead
comm = new SqlCommand("spGetNationalities", conn);
Databinding should work if your Nationality table has columns ID and Nationality
if (!Page.IsPostBack)
{
try
{
using (SqlConnection con = new SqlConnection("Data Source = NIPOON; Initial Catalog = CustomerOrders; Integrated Security = true"))
{
SqlCommand cmd = new SqlCommand("SELECT Name FROM Customer", con);
con.Open();
dropDownList.DataSource = cmd.ExecuteReader();
dropDownList.DataTextField = "Name";
dropDownList.DataValueField = "Name";
dropDownList.DataBind();
}
}
catch (Exception Ex)
{
Console.WriteLine("Error: " + Ex.Message);
}
GetData();
}

Cannot reuse open DataReader

I am writing a c# windows forms application and i am coming accross the error mentioned above. I think this is happening because i am opening an sql connection and reader object in my main form load object and then doing the same thing again in another click event handler. I am not sure what i need to do in order to change my code / stop this from happening (or if this is even the problem). I have tried turning MARS on in my connection string but this did not fix the problem. Below is my code.
namespace Excel_Importer
{
public partial class Export : Form
{
public Export()
{
InitializeComponent();
}
private void cmbItemLookup_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void Export_Load(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings ["dbconnection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("Select * From ExportItem", conn);
SqlDataReader rdr;
rdr = cmd.ExecuteReader();
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("ExportItemName", typeof(string));
dt.Load(rdr);
cmbItemLookup.DisplayMember = "ExportItemName";
cmbItemLookup.DataSource = dt;
conn.Close();
}
}
private void btnLoad_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd2 = new SqlCommand("Select * from " + cmbItemLookup.Text, conn);
SqlDataReader rdr2;
rdr2 = cmd2.ExecuteReader();
try
{
SqlDataAdapter ada = new SqlDataAdapter();
ada.SelectCommand = cmd2;
DataTable dt = new DataTable();
ada.Fill(dt);
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dgvExport.DataSource = bs;
ada.Update(dt);
conn.Close();
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
}
}
You need to close your DataReaders. They implement the IDisposable interface, so the simplest thing is to put them inside a using block:
using (rdr = cmd.ExecuteReader())
{
..
} // .NET always calls Dispose() for you here
Actually, you pretty much have to dispose of everything that implements IDisposable, or problems gonna happen.
As the other answer points out, you must tidy up your clicked event code:
private void btnLoad_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString) )
{
conn.Open();
using(SqlCommand cmd2 = new SqlCommand("Select * from " + cmbItemLookup.Text, conn) )
{
using(SqlDataReader rdr2= cmd2.ExecuteReader())
{
try
{
SqlDataAdapter ada = new SqlDataAdapter();
ada.SelectCommand = cmd2;
DataTable dt = new DataTable();
ada.Fill(dt);
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dgvExport.DataSource = bs;
ada.Update(dt);
conn.Close();
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
}
}
}

Datagridview with query in C#

I have 2 tables in MySql (privacy , lawsuit_under_500) ,
In privacy i have 2 columns (id , nameofcase ) ,
In lawsuit_under_500 4 columns(id,nameofcase,priceone,pricetwo) ,
I make a form with a datagridview and i want to execute this query :
select privacy.id,lawsuit_under_500.id,privacy.nameofcase, lawsuit_under_500.priceone, lawsuit_under_500.pricetwo
From privacy inner join lawsuit_under_500
where lawsuit_under_500.id=5 and privacy.id=1 || lawsuit_under_500.id=1 and privacy.id=2 || lawsuit_under_500.id=10 and privacy.id=3
ORDER BY privacy.id
In the form i have:
public Form55()
{
InitializeComponent();
}
private void Form55_Load(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
I have put the tables in my DataSet but I cant figure out how to make it. I tried to make privacyBindingSourse in the datagridview and i added manually 2 buttons for priceone and pricetwo put i cant put the query so i can get the information.
Any ideas/help how to make it ?
BEFORE YOU ANSWER IF YOU HAVE ANY QUESTION PLEASE ASK ME
using MySql.Data.MySqlClient;
MySqlConnection conn = new MySqlConnection("Your MY SQL connection");
MySqlCommand cmd = new MySqlCommand("Your Mysql query");
MySqlDataReader dr=cmd.ExecuteReader();
gridview1.datasource=dr;
gridview1.databind();
// try this also
connectionString = "Your Connection";
connection = new MySqlConnection(connectionString);
if (this.OpenConnection() == true)
{
mySqlDataAdapter = new MySqlDataAdapter("Your Query", connection);
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
dataGridView1.DataSource = DS.Tables[0];
//close connection
this.CloseConnection();
}
I made it with this way
private void Form56_Load(object sender, EventArgs e)
{
try
{
MySqlConnection cnn = new MySqlConnection("MY CONNECTION");
cnn.Open();
// - DEBUG
// MessageBox.Show("Connection successful!");
MySqlDataAdapter MyDA = new MySqlDataAdapter();
MyDA.SelectCommand = new MySqlCommand("MY QUERY", cnn);
DataTable table = new DataTable();
MyDA.Fill(table);
BindingSource bSource = new BindingSource();
bSource.DataSource = table;
dataGridView1.DataSource = bSource;
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
Close();
}
}
static public SqlCeConnection OpenSQL()
{
SqlCeConnection cncount = new SqlCeConnection(#"Data Source = " + Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + #"\Database.sdf; Password =''");
return cncount;
}
static public DataTable DoSelect( string strSQL)
{
SqlCeConnection cn = OpenSQL();
DataTable dtRetValue = new DataTable();
using (SqlCeDataAdapter da = new SqlCeDataAdapter())
{
using (SqlCeCommand cmd = cn.CreateCommand())
{
cmd.CommandText = strSQL;
da.SelectCommand = cmd;
if (cn.State == ConnectionState.Closed)
{
cn.Open();
}
try
{
//using (SqlCeDataReader reader = da.SelectCommand.ExecuteReader())
SqlCeDataReader metsDr = da.SelectCommand.ExecuteReader();
dtRetValue.Load(metsDr);
return dtRetValue;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error - DoSelect", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
return null;
}
}
}
}
Insert in Button
string sql1 = "YOURE QUERY ";
DataTable dt1 = SQLcode.DoSelect(sql1);
dgvcompany.DataSource = dt1;

Gridview in asp.net C#

I have two dropdownlist, corresponding to the values,gridview should be displayed,,and below is code for it..But i am not getting What's the problem in it!!
protected void ddlstudents_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlstudents.SelectedIndex > 0)
{
BindData();
}
}
private void BindData()
{
try
{
SQLiteConnection con = new SQLiteConnection("data source=C:\\ITS Database\\its.development.sqlite3");
string strquery = "select topics.name,course_coverages.progress from topics JOIN course_coverages on topics.id=course_coverages.topic_id where course_coverages.student_id=#studentid AND course_coverages.course_id=#courseid";
con.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.connection=con;
cmd = con.CreateCommand();
cmd.CommandText = strquery;
cmd.Parameters.AddWithValue("#studentid", ddlstudents.SelectedIndex);
cmd.Parameters.AddWithValue("#courseid", ddlcourse.SelectedValue);
SQLiteDataAdapter ada = new SQLiteDataAdapter(cmd.CommandText, con);
SQLiteCommandBuilder cbl = new SQLiteCommandBuilder(ada);
DataTable dt = new DataTable();
ada.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
catch (SQLiteException)
{
}
}
Any Help Would Be Appreciated!!
Thanks in Advance!!
Learn how to find the problem your self. if the gridview not showing correct data you can debug the application and find where it failed.
you have not given how you bind ddlstudents and ddlcourse , check the values you get for ddlstudents.SelectedIndex and ddlcourse.SelectedValue as you expected or not.
if values are correct, you can run the SQL statement on your database with above values and see the results.
If you really need to find the error, remove the try catch statement from your code,
If you catch the exception, do something with it. otherwise don't.
try this
protected void ddlstudents_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlstudents.SelectedIndex > 0)
{
BindData();
}
}
private void BindData()
{
try
{
SQLiteConnection con = new SQLiteConnection("data source=C:\\ITS Database\\its.development.sqlite3");
string strquery = "select topics.name,course_coverages.progress from topics JOIN course_coverages on topics.id=course_coverages.topic_id where course_coverages.student_id=#studentid AND course_coverages.course_id=#courseid";
con.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.connection=con;
cmd = con.CreateCommand();
cmd.CommandText = strquery;
cmd.Parameters.AddWithValue("#studentid", ddlstudents.SelectedValue);
cmd.Parameters.AddWithValue("#courseid", ddlcourse.SelectedValue);
SQLiteDataAdapter ada = new SQLiteDataAdapter(cmd.CommandText, con);
SQLiteCommandBuilder cbl = new SQLiteCommandBuilder(ada);
DataTable dt = new DataTable();
ada.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
catch (SQLiteException)
{
}
}

Categories

Resources