I am new to C# and have simple method to show data from a table DimCustomer. I am calling this method from a button but its not displaying data. Although when i debug my code i can see data, but not displaying it. Any suggestions please
private void ShowGridData()
{
// create a connection object
string ConnectionString = "Integrated Security=SSPI;" +
"database=AdventureWorksDW2012;" + "server=DESKTOP-L9L3SMT\\SQL2K12;";
SqlConnection conn = new SqlConnection(ConnectionString);
// open the connection
conn.Open();
// Create a DataTableMapping object
DataTableMapping myMapping = new DataTableMapping("DimCustomer", "mapCustomer");
SqlDataAdapter adapter = new SqlDataAdapter("Select * FROM DimCustomer where LastName='yang' and BirthDate='1966-04-08'", conn);
// Call DataAdapter's TableMappings.Add method
adapter.TableMappings.Add(myMapping);
// Create a DataSet object and Call DataAdapter's Fill method
DataSet ds = new DataSet();
adapter.Fill(ds, "DimCustomer");
dataGridView1.ColumnCount = 0;
dataGridView1.DataSource = ds.DefaultViewManager;
}
Can you please try this instead?
dataGridView1.DataSource = ds.Tables[0];
Related
While adding creating GUI in VS2019 you can add TableDataAdapter which will add/show Datagrid showing that tables data. with this code in designer this.data1TableAdapter.Fill(this.test1DataSet.data1);
But problem is if there are any changes in database/table they will not be reflected in that datagrid.
I tried using data1DataGridView.Update(); and data1DataGridView.Refresh(); but it literally does nothing.
than I added my database connection string as datasource.(I know thats stupid attempt, But I tried it anyway.) which obviously didn't worked and erased my whatever(non updated) data showing in datagrid.
So here is my question is there any simple way to update that automatically every time there is change in database/table ?
Disclaimer: I have it working but another way. I will share that too.
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:\Documents\test1.mdb";
OleDbCommand comm = new OleDbCommand("SELECT * FROM data1;", conn);
conn.Open();
OleDbDataAdapter dap = new OleDbDataAdapter(comm);
DataTable ds = new DataTable();
dap.Fill(ds);
data1DataGridView.DataSource = ds;
comm.ExecuteNonQuery();
conn.Close();
According to me there are two things you can do.
1- create a Refresh button and at that button call the userdefined function refresh
public void Refresh(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:\Documents\test1.mdb";
OleDbCommand comm = new OleDbCommand("SELECT * FROM data1;", conn);
conn.Open();
OleDbDataAdapter dap = new OleDbDataAdapter(comm);
DataTable ds = new DataTable();
dap.Fill(ds);
data1DataGridView.DataSource = ds;
comm.ExecuteNonQuery();
conn.Close();
}
this function rebind data to your new table every time you clicked
2- you can use timer control to refresh your data grid. I am pasting the link how to use timer control in c# you can follow it, and simply paste the above Refresh function definition in timer control. it will refresh your datagrid according to time interval you provide.
I have a return value from the stored procedure GetTeam, and I want it to be displayed in the Gridview. This is what I have, but it is not displaying in the gridview:
protected void getTeam()
{
SqlConnection con;
string CS = Configuration.Manager.ConnectionStrings["TEAM"].ConnectionString;
DataTable dt = new DataTable();
using(con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("GetTeam",con);
SqlDataAdapter da = new SqlAdapter(cmd);
da.fill(dt);
Gridview1.Datasource = dt;
Gridview1.Databind();
}
}
Could anyone help?
Here try this solution below, keep in this solution we are sending a parameter to help narrow our results to specific team.
using (SqlConnection conn = new SqlConnection())
{
//Connection string
conn.ConnectionString = ConnectionString.DataSourceString;
//Create adapter and assign store procedure name
SqlCommand cmmd = new SqlCommand()
{
CommandType = CommandType.StoredProcedure
};
// Assign to Command type
//exception is caught because it cannot find Stored Procedure
//Insert parameters into row from input text
cmmd.CommandText = "GetTeam";
// Send parameter
cmmd.Parameters.AddWithValue("#PGetDayTeam",
ShiftParameterTextBox.Text.Trim());
cmmd.Connection = conn;
try
{
conn.Open();
//If we do not receive any records
GridView2.EmptyDataText = "No Records Found";
GridView2.DataSource = cmmd.ExecuteReader();
GridView2.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
// Close and dispose connection
conn.Close();
conn.Dispose();
}
// select from grid
protected void GridView2_SelectedIndexChanging(Object sender, GridViewSelectEventArgs e)
{
GridViewRow row = GridView2.Rows[e.NewSelectedIndex];
string GetTeam = row.Cells[2].Text;
// You can use it in viewstate or what you choose.
ViewState["GetTeam"] = GetTeam;
}
The Fill operation then adds the rows to destination DataTable objects
in the DataSet, creating the DataTable objects if they do not already
exist. When creating DataTable objects, the Fill operation normally
creates only column name metadata. However, if the MissingSchemaAction
property is set to AddWithKey, appropriate primary keys and
constraints are also created.
You're using sql prosedure. So you already have a Colums' name. You don't need to use DataTable. The Sql adapter can fill dataset also. You need to use DataSet first.
public static DataSet ExecuteDataset(SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
//create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters);
//create the DataAdapter & DataSet
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
//fill the DataSet using default values for DataTable names, etc.
da.Fill(ds);
//return the dataset
return ds;
}
Then you can bind your Gridview with that one.
grdView.DataSource = ds;
grdView.DataBind();
I have a table called Departments where the column i wish to populate my combobox with is named DeptId. below is the datatable i created in my DAL class, but i cant for my life figure out how to put these values into deptCombobox in my form1 class. I am trying to attach it to a button named refreshButton_Click, but nothing works no matter what i try
//DAL
public DataTable fillDeptCombo()
{
SqlConnection con = new SqlConnection(#"Data Source=");
con.Open();
string queryText = "SELECT * FROM DEPARTMENT ";
SqlCommand cmd = new SqlCommand(queryText, con);
da = new SqlDataAdapter(cmd);
dt = new DataTable();
da.Fill(dt);
con.Close();
return dt;
}
//controller
public DataTable fillDeptCombo()
{
return dal.fillDeptCombo();
}
Any help would be greatly appreciated
You have mentioned "form1", I assume it is for windows forms.
In your form1 cs code, this should do it.
DAL dl=new DAL()
Datatable dt=DAL.fillDeptCombo()
combobox.datasource=dt;
combobox.valuemember="deptID" //replace this with your value
combobox.displayMember="DeptName" //replace this with your text
I have a little problem with populating my DevExpress Gridview, I want to have a two level gridview and using SqlCommand. At first I created a Dataset and added two tables and also defined relation for them. But it does not work. Can you help me find my problem?
Here is my code
string owner = "SELECT [OBJECTID],[Name] ,[Family] ,[Father] ,[Dftarche] ,[Birthday] ,[education] ,[home_address] ,[farm_address] ,[ensurance] ,[phone] ,[home_number] ,[owner_id] FROM [dbo].[OWNER]";
string property = "SELECT [number] ,[owner_ID] ,[GPSId] ,[Energy],[corp_type] ,[Pool],[irrigation] ,[variety] ,[trees] ,[utilizat] ,[address] ,[water_hour] ,[w_source] ,[w_inche],[w_dore],[NoeMalekiat],[MotevasetBardasht],[Area] ,[OBJECTID],[Shape] FROM [dbo].[Property] ";
string strConnString = Properties.Settings.Default.land_gisConnectionString;
SqlConnection con = new SqlConnection(strConnString);
con.Open();
SqlCommand command = new SqlCommand(owner, con);
SqlDataAdapter adapter = new SqlDataAdapter();
System.Data.DataSet dsMain = new System.Data.DataSet();
adapter.SelectCommand = command;
adapter.Fill(dsMain, "First Table");
adapter.SelectCommand.CommandText = property;
adapter.Fill(dsMain, "Second Table");
dsMain.Tables.Add(iFeatureSet.DataTable.Copy());
adapter.Dispose();
command.Dispose();
DataRelation newRelation = new DataRelation("املاک شخصی", dsMain.Tables["First Table"].Columns["owner_id"], dsMain.Tables["Second Table"].Columns["owner_ID"]);
dsMain.Relations.Add(newRelation);
GridAttrebuteTable.DataSource = dsMain.Tables[2];
// gridView5.DataSource = dsMain.Tables[1];
dataGridView1.DataSource = dsMain;
I searched and found this http://msdn.microsoft.com/en-us/library/bh8kx08z.aspx and it seems my code is right but it does not show anything in grids
Thank you very much for your help
I Could figure out how to fix it.It works fine now(Above Code is edited) but now If I add a new DataTable I do not know why it does not work again
You need a new GridView for each detail table. You can't display both a master and detail in the same GridView.
Try this example
I am merging two datasets and I wish that duplicate rows are only bind once ,how can I achieve this ?
protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
{
showRelatedcat();
DataSet ds = new DataSet();
DataSet ds_frd = new DataSet();
String frdQuery = my query
String newquery = my other query
String queryString = another one
try
{
// Connect to the database and run the query.
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter adapter = new SqlDataAdapter(newquery, connection);
SqlDataAdapter adapter1 = new SqlDataAdapter(frdQuery, connection);
// Fill the DataSet.
adapter1.Fill(ds_frd);
adapter.Fill(ds);
ds.Merge(ds_frd, true);
connection.Close();
}
catch (Exception ex)
{
// The connection failed. Display an error message.
//Message.Text = "Unable to connect to the database.";
}
RadGrid1.DataSource = ds.Tables[0].;
}
both queries have some rows as common .
you can merge dataset using Dataset.Merge using IEnumerable function
http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/ebe7e4c2-2cad-4a9d-9134-2732d1e05664
it allows you to get only one value in duplicate case