I want to show my data in grid view in my Asp.new c# form.
I am using Wamp Server's MySQL database.
I have tired a lot for binding database with grid view.
Please do help.
my code :
public partial class Temp : System.Web.UI.Page
{
string conString = ConfigurationManager.ConnectionStrings["AASProject"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection(conString);
con.Open();
gvFoodDetail.RowEditing+= new GridViewEditEventHandler(gvFoodDetail_RowEditing);
gvFoodDetail.RowDeleting += new GridViewDeleteEventHandler(gvFoodDetail_RowDeleting);
gvFoodDetail.RowUpdating += new GridViewUpdateEventHandler(gvFoodDetail_RowUpdating);
//gvFoodDetail_RowCancelingEdit += new GridViewCancelEditEventArgs(gv);
// gvFoodDetail.RowEditing += new GridViewEditEventHandler(gvFoodDetail_RowEditing);
// gvFoodDetail.RowDeleting += new GridViewDeleteEventHandler(gvFoodDetail_RowDeleting);
// gvFoodDetail.RowUpdating += new GridViewUpdateEventHandler(gvFoodDetail_RowUpdating);
// gvFoodDetail.RowCancelingEdit += new GridViewCancelEditEventHandler(gvFoodDetail_RowCancelingEdit);
gvFoodDetail.PageIndexChanging += new GridViewPageEventHandler(gvFoodDetail_PageIndexChanging);
if (!IsPostBack)
{
gvFoodDetail.Visible = true;
loadFoodDB();
}
}
public void loadFoodDB()
{
string getFoodDetails = "Select Emp_ID,intime,outtime,date From datetime";
MySqlConnection con = new MySqlConnection(conString);
con.Open();
MySqlCommand cmd = new MySqlCommand(getFoodDetails, con);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
gvFoodDetail.DataSource = dt;
gvFoodDetail.DataBind();
}
datagridview.Datasource = datasource
datagridview.databind()
This should set and show the data. You have to handle the columns and everything manually or automatically.
Related
I have a Dataset that I fill with two sql tables in the Page_Load event. I fill my DropDownList ddlAirport00 with the values of the first table. But I can not access the filled dataset from the ddlAirport00_SelectedIndexChanged(). It's like the dataset is empty or a Scope of variables trouble.
Someone can help me?
public partial class _Default : System.Web.UI.Page
{
public DataSet ds = new DataSet();
}
my Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String CS = ConfigurationManager.ConnectionStrings["MyDatabaseConnectionString1"].ConnectionString;
using (SqlConnection scon = new SqlConnection(CS))
{
//this.ds = new DataSet();
sda = new SqlDataAdapter("Select * from Aeropuerto", scon);
sda.Fill(ds, "Aeropuerto");
sda = new SqlDataAdapter("Select * from ALocalidad", scon);
sda.Fill(ds, "Localidad");
sda = new SqlDataAdapter("Select * from Tramo", scon);
sda.Fill(ds, "Tramo");
}
}
And My DDL SelectedIndexChanged() ** I Use Ajax to change the testeeric.Text
protected void ddlAirport00_SelectedIndexChanged(object sender, EventArgs e)
{
if (ds.Tables.Contains("Tramo"))
{
testeeric.Text = DateTime.Now.ToString();
}
else
{
testeeric.Text = "Brasil";
}
}
Since the data retrieving logic is located inside if (!IsPostBack), it is called only at initial page load.
So, you will need to retrieve the data from database again inside SelectedIndexChanged event.
protected void ddlAirport00_SelectedIndexChanged(object sender, EventArgs e)
{
String CS = CnfigurationManager.ConnectionStrings
["MyDatabaseConnectionString1"].ConnectionString;
using (SqlConnection scon = new SqlConnection(CS))
{
sda = new SqlDataAdapter("Select * from Tramo", scon);
sda.Fill(ds, "Tramo");
// Do something.
if (ds.Tables.Contains("Tramo"))
{
testeeric.Text = DateTime.Now.ToString();
}
else
{
testeeric.Text = "Brasil";
}
}
}
I have combobox in my form which display value from database. I want one default value so I use .text property also and on selected index changed event the label display the corresponding value of the database the code is not working
string cstr = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
private void AddStock_Load(object sender, EventArgs e)
{
bindcombo();
}
private void bindcombo()
{
SqlConnection con = new SqlConnection(cstr);
SqlDataAdapter da = new SqlDataAdapter("SELECT Dname FROM dealer", con);
DataTable dt = new DataTable();
da.Fill(dt);
cmbdealer.DataSource = dt;
cmbdealer.DisplayMember = "Dname";
cmbdealer.Text = "select-Dealer";
con.Close();
}
private void cmbdealer_SelectedIndexChanged(object sender, EventArgs e)
{
dealerdetails();
}
private void dealerdetails()
{
SqlConnection con = new SqlConnection(cstr);
SqlCommand cmd = new SqlCommand("select * from dealer where Dname='" + cmbdealer.Text + "'", con);
con.Open();
SqlDataReader re = cmd.ExecuteReader();
while (re.Read())
{
lbdl.Text = re["Ddlno"].ToString();
lbgst.Text = re["Dgstno"].ToString();
lbadd.Text = re["Daddress"].ToString();
}
}
the above code is working fine but when the form is load all the 3 label shows the database value of the first entry of my dealer table without selecting and value from combobox.
I have a DataRepeater template control with 2 textboxes which I want to associate data from a mysql table
When I run this program I get the representation on my DataRepeater the number of rows existing in my mysql table
RESULT
my question is how to associate the data to those textboxes
private void Form1_Load(object sender, EventArgs e)
{
BindLviewData();
}
protected void BindLviewData()
{
System.Data.DataTable dt = new System.Data.DataTable("db.myTable");
MySqlConnection dbConn = new MySqlConnection("Server = localhost; Database = db; Uid = wwww; Pwd = www; ");
dbConn.Open();
string query = string.Format("SELECT Col1,Col2 FROM myTable");
MySqlCommand cmd = new MySqlCommand(query, dbConn);
MySqlDataAdapter returnVal = new MySqlDataAdapter(cmd);
returnVal.Fill(dt);
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dataRepeater1.DataSource = bs;
dbConn.Close();
}
I'm trying to update a table from the gridview of tool to the SQL database. The problem is it's not getting updated in the database.
Below is my code for the button click which updates the database:
while debugging the code i found that the data table DT is fetching only the source values not the updated one in the grid view....
Is there any property in the grid view which accepts these change and updates the DT table ?
public partial class BusinessRules : Form
{
//Declaration Part
private SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=AnimalProductsCoSD;Integrated Security=True");
private string sqlconn; // query and sql connection
private SqlDataAdapter SDA = new SqlDataAdapter();
DataTable DT = new DataTable();
SqlCommandBuilder scb = new SqlCommandBuilder();
private void button_retreive_Click(object sender, EventArgs e)
{
string commandText = "CoSD.RetreiveBusinessRulesTool";
SqlCommand cmd = new SqlCommand(commandText, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#BusinessType", SqlDbType.NVarChar, 60).Value = comboBox_BusinessType.Text;
cmd.Parameters.Add("#CommodityGroup", SqlDbType.VarChar, 60).Value = comboBox_group.Text;
try
{
con.Open();
SDA.SelectCommand = cmd;
DT = new DataTable();
SDA.Fill(DT);
int count1 = DT.Rows.Count;
if (DT.Rows.Count > 0)
{
dataGridView.DataSource = DT;
dataGridView.Columns[0].DefaultCellStyle.ForeColor = Color.Gray;
dataGridView.Columns[0].ReadOnly = true;
}
else
{
MessageBox.Show("No Business Rules Found");
}
}
catch (SqlException ex)
{
MessageBox.Show("Error : " + ex.Message);
}
finally
{
con.Close();
}
}
private void button_update_Click(object sender, EventArgs e)
{
try
{
if (MessageBox.Show("Do you really want to Update these values?", "Confirm Update", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
scb = new SqlCommandBuilder(SDA);
SDA.Update(DT);
// confirm
MessageBox.Show("Updates successfully submitted to CoSD");
}
else
{
return;
}
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
}
In the try, put this
scb = new SqlCommandBuilder(sda);
sda.Update(dt);
In your initializer call
SqlDataAdapter sda= new SqlDataAdapter("SELECT * FROM someWhere", connectionString);
DataTable dt = new DataTable();
The problem is that you refresh the datagridview before submitting the changes, thus deleting anything inputted
**** EDIT ****
This is exactly what my code in a project I did a little while back looks like:
namespace TowerSearch
{
public partial class EditParts : Form
{
const string conString = ConString.conString;
static DataClasses1DataContext PartsLog = new DataClasses1DataContext(conString);
static Table<Part> listOfParts = PartsLog.GetTable<Part>();
SqlDataAdapter sda;
SqlCommandBuilder scb;
DataTable dt;
public EditParts()
{
InitializeComponent();
}
//Load and refresh the dataGridView
private void showData()
{
SqlConnection con = new SqlConnection(conString);
sda = new SqlDataAdapter("SELECT * FROM Parts", con);
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
private void EditParts_Load(object sender, EventArgs e)
{
showData();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
dataGridView1.Refresh();
scb = new SqlCommandBuilder(sda);
sda.Update(dt);
MessageBox.Show("Saved");
showData();
}
catch (Exception ee)
{
MessageBox.Show("There is an error in the data!\nCheck if there are any blank spots besides Quantity.");
}
}
}
}
That definitely works, so try the code with the show data. I'd suggest just copying it verbatim first to see if it would work.
**** EDIT 2 ****
Another thing that you could try if you haven't managed to get it already is add a bindingSource. To do this, drag a bindingSource onto your dataGridView and then set the DataSource option to the table of the DB that you wan't to display
Hope that helps!
i have a textbox and listbox in a winform app. when i type a value(i.e,string) in the textbox i want the listbox to show the values from datatable and when i am selecting a particular value from listbox it will display in textbox .
code:
private void txtIName_TextChanged(object sender, EventArgs e)
{
string constring = "Data Source=.;Initial Catalog=Test;User Id=sa;Password=admin#123";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT distinct * FROM Item_Details", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (dt = new DataTable())
{
sda.Fill(dt);
DataView dv = new DataView(dt);
dv.RowFilter = string.Format("IName Like '%{0}%'", txtIName.Text);
listBox1.Visible = true;
listBox1.DataSource = dv;
}
}
}
}
}
but i got the output in listbox like "system.data.datarow". By debugging i can seen that rows which i want, in dataview 'dv'. what i am missing here? thanks.
You don't need to load data each time the TextChanged event fires. It's enough to load data in Load event of your form and then in TextChanged just filter the data. Then using an event like DoubleClick of ListBox set the text of TextBox:
private DataTable dataTable = new DataTable();
private void Form1_Load(object sender, EventArgs e)
{
string constring = #"Data Source=.;Initial Catalog=Test;User Id=sa;Password=admin#123";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlDataAdapter sda = new SqlDataAdapter("SELECT distinct * FROM Item_Details", con))
{
sda.Fill(dataTable);
}
}
this.listBox1.DataSource = new DataView(dataTable);
this.listBox1.DisplayMember = "IName";
this.listBox1.Visible = false;
}
private void txtIName_TextChanged(object sender, EventArgs e)
{
var dv = (DataView)this.listBox1.DataSource;
dv.RowFilter = string.Format("IName Like '%{0}%'", txtIName.Text);
listBox1.Visible = true;
}
private void listBox1_DoubleClick(object sender, EventArgs e)
{
var item = (DataRowView)listBox1.SelectedItem;
if (item != null)
this.txtIName.Text = item["IName"].ToString();
else
this.txtIName.Text = "";
this.listBox1.Visible = false;
}
Don't forget to attach Form1_Load, txtIName_TextChanged and listBox1_DoubleClick handlers to events.
You must specify your DisplayMember, it must be some Field in your DataView
listBox1.DisplayMember = "Your Field"
then you can suscribe to the event SelectedValueChanged :
listBox1.SelectedValueChanged += new EventHandler(listBox1_SelectedValueChanged);
visual studio create for you an event handler
void listBox1_SelectedValueChanged(object sender, EventArgs e)
{
// you get your selected item here
}
hope it helps