First GridView dissapears when binding a second GridView in code - c#

I'm having a problem with a couple of gridviews that are filled from the code behind.
When I fill and databind GridView1 on it's own it works fine.
I then added the code to fill and bind GridView2 which displays but GridView1 dissapears completely.
If I comment out GridView2.DataBind() then GridView1 then appears again.
I can't work out what is going on.
Incidentaly if I change GridView2 for a DropDownList or a CheckBoxList then the same problem occurs, but if I change it for a ListBox then GridView1 appears.
protected void Page_Load(object sender, EventArgs e)
{
Int32 chaID = 20;
Int32 slots = 14;
String ConnectionString = WebConfigurationManager.ConnectionStrings["horizonConnectionString"].ToString();
String selectSQL = "SELECT chassis.ChassisName, srv.ChassisPosition, srv.ServerName, srv.ChassisID, srv.LocationID, chassis.LocationID AS ChaLocationID FROM srv INNER JOIN chassis ON srv.ChassisID = chassis.ChassisID WHERE (srv.ChassisID = '" + chaID + "') ORDER BY chassis.ChassisName, srv.ChassisPosition";
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
DataTable dt2 = new DataTable();
DataView dv = new DataView();
try
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(selectSQL, con);
sda.Fill(dt2);
dv = dt2.DefaultView;
}
catch (Exception)
{
}
try
{
int searchIndex;
dv.Sort = "ChassisPosition";
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Bay", typeof(Int32)));
dt.Columns.Add(new DataColumn("Server", typeof(String)));
for (int i = 0; i <= slots - 1; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i + 1;
searchIndex = dv.Find(i + 1);
if (searchIndex != -1)
{
dr[1] = dv[searchIndex][2].ToString();
}
else
{
dr[1] = "-----";
}
dt.Rows.Add(dr);
}
this.GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception)
{
}
ConnectionString = WebConfigurationManager.ConnectionStrings["horizonConnectionString"].ToString();
selectSQL = "SELECT [ServerName], [ServerID], [FarmName], [LMG] FROM [srv] ORDER BY [ServerName]";
con = new SqlConnection(ConnectionString);
cmd = new SqlCommand(selectSQL, con);
DataTable dt3 = new DataTable();
try
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(selectSQL, con);
sda.Fill(dt3);
this.GridView2.DataSource = dt3;
GridView2.DataBind();
}
catch (Exception)
{
}
}

you are using the same instance of SqlDataAdapter for two connections at the same time.
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
the SqlDataAdapter object has been named "sda" twice in "page_load" method.
SqlDataAdapter sda = new SqlDataAdapter(selectSQL, con);
SqlDataAdapter "sda" is already binding to GridView1. this data binding will be lost if U change or re-assign this object.

Related

How can I set the first line of the combo box, which is connected with a database, empty?

How can I set the first line of Combobox empty in my code?
This is the function that is called when the form loads and it inserts the options on the Combobox.
private void preencherComboDpt()
{ carregandoComboDepartamentos = true;
NpgsqlConnection conn = new NpgsqlConnection();
try
{
conn = new NpgsqlConnection(connstring);
string query = "select * from departamento order by departamento";
NpgsqlCommand cmd = new NpgsqlCommand(query, conn);
cmd.CommandText = query;
conn.Open();
NpgsqlDataReader drd = cmd.ExecuteReader();
DataTable dt = new DataTable("tabela");
dt.Columns.Add("departamento_id", typeof(int));
dt.Columns.Add("departamento", typeof(string));
while (drd.Read())
{
DataRow row = dt.NewRow();
row["departamento_id"] = int.Parse(drd["departamento_id"].ToString());
row["departamento"] = drd["departamento"].ToString();
dt.Rows.Add(row);
}
cobUnivDep.DataSource = dt.DefaultView;
cobUnivDep.DisplayMember = "departamento";
cobUnivDep.ValueMember = "departamento_id";
}
catch
{
MessageBox.Show("Error ");
}
carregandoComboDepartamentos = false;
}
I already tried inserting the line cobUnivDep.SelectedIndex = null, but it doesn't work.

Is there any Way to show Empty GridView On pageLoad event?

Hope You all Are Fine
Can any one help me kindly i have a grid view that fetch tha record from database but show all the previous data which i entered by the grid but now i want to show the all data which i entering till the pageload even called, when page load that should not show all the entered records.
Thanks in Advance
Here is my code behind work
protected void BindData()
{
SqlConnection conne = new SqlConnection("Data Source=192.168.0.65;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=mushko");
DataSet ds = new DataSet();
conne.Open();
string cmdstr = "SELECT * FROM OPR1 ";
SqlCommand cmd = new SqlCommand(cmdstr, conne);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
cmd.ExecuteNonQuery();
conne.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
// GridView1.DataSource =null;
// GridView1.DataSource = ds;
// GridView1.DataBind();
//ds = null;
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection conne = new SqlConnection("Data Source=192.168.0.65;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=mushko");
conne.Open();
if (e.CommandName.Equals("ADD"))
{
Calendar txtOpenDate = (Calendar)GridView1.FooterRow.FindControl("txtOpenDate");
TextBox txtCloseDate = (TextBox)GridView1.FooterRow.FindControl("txtCloseDate");
DropDownList DropDownListoppr = (DropDownList)GridView1.FooterRow.FindControl("DropDownListoppr");
DropDownList DropDownListStages = (DropDownList)GridView1.FooterRow.FindControl("DropDownListStages");
TextBox txtAddLine = (TextBox)GridView1.FooterRow.FindControl("txtAddLine");
TextBox txtStages = (TextBox)GridView1.FooterRow.FindControl("txtStages");
TextBox txtAddOppId = (TextBox)GridView1.FooterRow.FindControl("txtAddOppId");
string cmdstr = "insert into OPR1(OpenDate,CloseDate,SlpCode,Step_Id,Line,OpprId) values(#txtOpenDate,#txtCloseDate,#SlpCode,#Step_Id,#txtAddLine,#txtAddOppId)";
SqlCommand cmd = new SqlCommand(cmdstr, conne);
cmd.Parameters.AddWithValue("#txtOpenDate", txtOpenDate.TodaysDate);
cmd.Parameters.AddWithValue("#txtCloseDate", txtCloseDate.Text);
cmd.Parameters.AddWithValue("#Step_Id", DropDownListStages.SelectedValue.ToString()); // SelectedItem.ToString());
cmd.Parameters.AddWithValue("#SlpCode", DropDownListoppr.SelectedValue.ToString()); // SelectedItem.ToString());
cmd.Parameters.AddWithValue("#txtStages", txtStages.Text);
cmd.Parameters.AddWithValue("#txtAddLine", txtAddLine.Text);
cmd.Parameters.AddWithValue("#txtAddOppId", txtAddOppId.Text);
cmd.ExecuteNonQuery();
// this.TextBox1.Text = DropDownList1.SelectedItem.ToString();
// this.TextBox3.Text = DropDownList1.SelectedValue.ToString();
BindData();
conne.Close();
}
}
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList DropDownListoppr = (DropDownList)e.Row.FindControl("DropDownListoppr");
DropDownList DropDownListStages = (DropDownList)e.Row.FindControl("DropDownListStages");
DataTable CardCode = new DataTable();
DataTable CardCode1 = new DataTable();
SqlConnection connection = new SqlConnection("Data Source=192.168.0.65;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=mushko");
using (connection)
{
// SqlCommand theCommand = new SqlCommand("select distinct T1.SlpCode,T1.SlpName,T3.StepId,T3.Descript from OSLP T1 left join OPR1 T2 on T1.SlpCode=T2.SlpCode right join OOST T3 on T3.StepId=t2.Step_Id ", connection);
SqlCommand theCommand = new SqlCommand("select SlpCode,SlpName from OSLP ", connection);
SqlCommand theCommand1 = new SqlCommand("select Distinct StepId, Descript from OOST ", connection);
SqlDataAdapter adapter = new SqlDataAdapter(theCommand);
SqlDataAdapter adapter1 = new SqlDataAdapter(theCommand1);
adapter.Fill(CardCode);
adapter1.Fill(CardCode1);
//DropDownList7.DataSource = CardCode;
//DropDownList7.DataTextField = "SlpName";
//DropDownList7.DataValueField = "SlpCode";
//DropDownList7.DataBind();
if (CardCode.Rows.Count > 0)
{
for (int i = 0; i < CardCode.Rows.Count; i++)
{
string name3 = CardCode.Rows[i]["SlpName"].ToString();
string slpCode = CardCode.Rows[i]["SlpCode"].ToString();
DropDownListoppr.Items.Add(new ListItem(name3, slpCode));
}
}
if (CardCode1.Rows.Count > 0)
{
for (int j = 0; j < CardCode1.Rows.Count; j++)
{
string name4 = CardCode1.Rows[j]["Descript"].ToString();
string stageCode = CardCode1.Rows[j]["StepId"].ToString();
DropDownListStages.Items.Add(new ListItem(name4, stageCode));
}
}
}
}
}
If you want to keep the grid empty on page load event, then do not write the code to bind it on Page Load event, instead write the code on"Add Button" click event(if that's what you want).
For showing empty record Grid You can Use EmptyDataTemplate.
For more you can try this Link

combobox Selected Text changed event not firing

This is my code. After adding data through DataSource, The SelectedIndexChanged event is not firing.
try
{
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
//comboBox1.Items.Clear();
comboBox1.ResetText();
Cn.Open();
SqlCommand Cd = new SqlCommand("Select Distinct Mobile From Client_Details Where Branch = '" + label2.Text + "'", Cn);
SqlDataReader da = Cd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Mobile", typeof(string));
dt.Load(da);
comboBox1.DisplayMember = "Mobile";
comboBox1.DataSource = dt;
comboBox1.SelectedItem = "<Select>";
}
catch
{
}
finally
{
Cn.Close();
Clear();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//Label CBSL = new Label();
//string CBSL = this.comboBox1.SelectedItem.ToString();
if (comboBox9.Text == "Client")
{
Update_Read_Client();
}
else if (comboBox9.Text == "Customer")
{
Update_Read();
}
}
It selects the first value again and again.
I had tried DropDownStye = DropDownList., But it become dormant. No values is added.
Any help to resolve my problem.
I'm not sure if you have "< Select >" item saved in your database. Also, when using DataTable it's easier to fill it using SqlDataAdapter. You should also use parameters instead of string concat when you're writing your query like this and using keyword closes your connection automatically when you're done using it. I'd write it like this probably:
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"SELECT DISTINCT Mobile
FROM Client_Details
WHERE Branch = #Branch";
cmd.Parameters.AddWithValue("#Branch", label2.Text);
try
{
var dt = new DataTable();
dt.Columns.Add("Mobile", typeof(string));
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
DataRow row = dt.NewRow();
row["Mobile"] = "<Select>";
dt.Rows.InsertAt(row, 0);
comboBox1.DisplayMember = "Mobile";
comboBox1.DataSource = dt;
comboBox1.SelectedItem = "<Select>";
}
catch
{
throw;
}
}

cannot load data into datagridview C# for a multitable sql query

I have a windows application C#
Where i have a datagridview1 where i need to retrieve a multitable data query
When the data is being retrieved from the table,it need to be filtered also at the same time
The problem that i am facing that the data is not been loaded although in the LocalWindows shows
The problem is The data is not being loaded in the datagridview
I can see the data is being loaded in the datagridview through the autos watch in visual studio-i have given the output in the end
what did i do wrong ?
//CODE
private void getData(string selectquery)
{
try
{
// string qryText1 = #"SELECT FEE_HEAD.FEE_HEAD_NAME, FEE_AMOUNT.FEE_HEAD_AMOUNT, FEE_AMOUNT.CLASS_ID FROM FEE_AMOUNT INNER JOIN FEE_HEAD ON FEE_AMOUNT.FEE_HEAD_ID = FEE_HEAD.ID";
SqlConnection con = new SqlConnection(#"Data Source=SRINATH-PC\SQLEXPRESS;Initial Catalog=BFMS;Integrated Security=True");
SqlCommand command = new SqlCommand(selectquery, con);
con.Open();
SqlDataAdapter dataAdapter1 = new SqlDataAdapter();
dataAdapter1.SelectCommand = command;
DataTable dataT = new DataTable();
dataAdapter1.Fill(dataT);
BindingSource bs = new BindingSource();
bs.DataSource = dataT;
dataGridView1.DataSource = bs;
dataAdapter1.Update(dataT);
dataGridView1.Refresh();
con.Close();
}
catch (SqlException ex1)
{
MessageBox.Show(ex1.ToString());
}
}
//LOCAL WATCH VIEW
Count 28 int+ Current {System.Data.DataRowView} object {System.Data.DataRowView}
DataMember "" string
RowCount 29 int
RowHeadersBorderStyle Raised System.Windows.Forms.DataGridViewHeaderBorderStyle
the code is working perfectly
public Form1()
{
InitializeComponent();
string query = "select * from benefitplans";
getData(query);
}
and then
private void getData(string selectquery)
{
try
{
// string qryText1 = #"SELECT FEE_HEAD.FEE_HEAD_NAME, FEE_AMOUNT.FEE_HEAD_AMOUNT, FEE_AMOUNT.CLASS_ID FROM FEE_AMOUNT INNER JOIN FEE_HEAD ON FEE_AMOUNT.FEE_HEAD_ID = FEE_HEAD.ID";
SqlConnection con = new SqlConnection(#"Data Source=392;User id=sa; Password=manage#123;Initial Catalog=Benefit;Pooling=False");
SqlCommand command = new SqlCommand(selectquery, con);
con.Open();
SqlDataAdapter dataAdapter1 = new SqlDataAdapter();
dataAdapter1.SelectCommand = command;
DataTable dataT = new DataTable();
dataAdapter1.Fill(dataT);
BindingSource bs = new BindingSource();
bs.DataSource = dataT;
dataGridView1.DataSource = bs;
dataAdapter1.Update(dataT);
dataGridView1.Refresh();
con.Close();
}
catch (SqlException ex1)
{
MessageBox.Show(ex1.ToString());
}
}
Try replacing these lines
SqlDataAdapter dataAdapter1 = new SqlDataAdapter();
dataAdapter1.SelectCommand = command;
DataTable dataT = new DataTable();
dataAdapter1.Fill(dataT);
BindingSource bs = new BindingSource();
bs.DataSource = dataT;
dataGridView1.DataSource = bs;
dataAdapter1.Update(dataT);
dataGridView1.Refresh();
con.Close();
with
SqlDataAdapter dataAdapter1 = new SqlDataAdapter();
dataAdapter1.SelectCommand = command;
DataSet dataS = new DataSet();
dataAdapter1.Fill(dataS);
dataGridView1.DataSource = dataS;
con.Close();
Hope, this may help.
We need to use display the Columns for the Datagridview using
dataGridView1.Columns[0].Name = "FEE_HEAD_NAME";
ataGridView1.Columns[0].HeaderText = "FEE_HEAD_NAME";
dataGridView1.Columns[0].DataPropertyName = "FEE_HEAD_NAME";
dataGridView1.Columns[1].HeaderText = "FEE_HEAD_AMOUNT";
dataGridView1.Columns[1].Name = "FEE_HEAD_AMOUNT";
dataGridView1.Columns[1].DataPropertyName = "FEE_HEAD_AMOUNT";
Anyways Thanks for the reply everyone

Populate a datagridview with sql query results

I'm trying to present query results, but I keep getting a blank data grid.
It's like the data itself is not visible
Here is my code:
private void Employee_Report_Load(object sender, EventArgs e)
{
string select = "SELECT * FROM tblEmployee";
Connection c = new Connection();
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, c.con); //c.con is the connection string
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource1.DataSource = table;
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bindingSource1;
}
What's wrong with this code?
Here's your code fixed up. Next forget bindingsource
var select = "SELECT * FROM tblEmployee";
var c = new SqlConnection(yourConnectionString); // Your Connection String here
var dataAdapter = new SqlDataAdapter(select, c);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
var ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds.Tables[0];
String strConnection = Properties.Settings.Default.BooksConnectionString;
SqlConnection con = new SqlConnection(strConnection);
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select * from titles";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.DataSource = dtRecord;
You don't need bindingSource1
Just set dataGridView1.DataSource = table;
Try binding your DataGridView to the DefaultView of the DataTable:
dataGridView1.DataSource = table.DefaultView;
This is suppose to be the safest and error pron query :
public void Load_Data()
{
using (SqlConnection connection = new SqlConnection(DatabaseServices.connectionString)) //use your connection string here
{
var bindingSource = new BindingSource();
string fetachSlidesRecentSQL = "select top (50) * from dbo.slides order by created_date desc";
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(fetachSlidesRecentSQL, connection))
{
try
{
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
dataAdapter.Fill(table);
bindingSource.DataSource = table;
recent_slides_grd_view.ReadOnly = true;
recent_slides_grd_view.DataSource = bindingSource;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message.ToString(), "ERROR Loading");
}
finally
{
connection.Close();
}
}
}
}
You may get a blank data grid if you set the data Source to a Dataset that you added to the form but is not being used. Set this to None if you are programatically setting your dataSource based on the above codes.
You may try this sample, and always check your Connection String, you can use this example with or with out bindingsource you can load the data to datagridview.
private void Employee_Report_Load(object sender, EventArgs e)
{
var table = new DataTable();
var connection = "ConnectionString";
using (var con = new SqlConnection { ConnectionString = connection })
{
using (var command = new SqlCommand { Connection = con })
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
try
{
command.CommandText = #"SELECT * FROM tblEmployee";
table.Load(command.ExecuteReader());
bindingSource1.DataSource = table;
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bindingSource1;
}
catch(SqlException ex)
{
MessageBox.Show(ex.Message + " sql query error.");
}
}
}
}
you have to add the property Tables to the DataGridView Data Source
dataGridView1.DataSource = table.Tables[0];
if you are using mysql this code you can use.
string con = "SERVER=localhost; user id=root; password=; database=databasename";
private void loaddata()
{
MySqlConnection connect = new MySqlConnection(con);
connect.Open();
try
{
MySqlCommand cmd = connect.CreateCommand();
cmd.CommandText = "SELECT * FROM DATA1";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
datagrid.DataSource = dt;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Years late but here's the simplest for others in case.
String connectionString = #"Data Source=LOCALHOST;Initial Catalog=DB;Integrated Security=true";
SqlConnection cnn = new SqlConnection(connectionString);
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM tblEmployee;", cnn);
DataTable data = new DataTable();
sda.Fill(data);
DataGridView1.DataSource = data;
Using DataSet is not necessary and DataTable should be good enough. SQLCommandBuilder is unnecessary either.
I think this professional way to Write from start, but you can use this code with MySQL bout I think they both are the same:
1/
using System.Data; AND using MySql.Data.MySqlClient;
2/
MySqlConnection con = new MySqlConnection("datasource=172.16.2.104;port=3306;server=localhost;database=DB_Name=root;password=DB_Password;sslmode=none;charset=utf8;");
MySqlCommand cmd = new MySqlCommand();
3/
public void SetCommand(string SQL)
{
cmd.Connection = con;
cmd.CommandText = SQL;
}
private void FillGrid()
{
SetCommand("SELECT * FROM `transport_db`ORDER BY `id` DESC LIMIT 15");
DataTable tbl = new DataTable();
tbl.Load(cmd.ExecuteReader());
dataGridView1.DataSource = tbl;
}
for oracle:
var connString = new ConfigurationBuilder().AddJsonFile("AppSettings.json").Build()["ConnectionString"];
OracleConnection connection = new OracleConnection();
connection.ConnectionString = connString;
connection.Open();
var dataAdapter = new OracleDataAdapter("SELECT * FROM TABLE", connection);
var dataSet = new DataSet();
dataAdapter.Fill(dataSet);

Categories

Resources