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
Related
I have a combobox that is filled from a database conditionally by checking off one of 10 checkboxes. Each of the 10 checkboxes contains the code below, which selects a portion of column based on a value in column2.
private void Check1_CheckedChanged(object sender, EventArgs e)
{
if (Check1.CheckState == CheckState.Checked)
{
// SQL Server connection
SqlConnection conn = new SqlConnection(#"Server = Server; Database = DB; Integrated Security = True");
DataSet ds = new DataSet();
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT [Column1] FROM [DB].[dbo].[Table1] WHERE [Column2] = 50", conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
combo1.DisplayMember = "Column1";
combo1.ValueMember = "ID";
combo1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
//Exception Message
}
finally
{
conn.Close();
conn.Dispose();
}
}
if (Check1.CheckState == CheckState.Unchecked)
{
combo1.DataSource = null;
}
Therefore, it is rather trivial to fill the combobox with each separate condition. What I want to do that I'm not sure of the approach, however, is that when more than one checkbox is checked, the combobox will display the data from every checked checkbox at once (all this data will be from the same column). Moreover, when a single checkbox is then unchecked, I only want it to remove its own dataset from the combobox and not everything.
Is this possible?
I think it's possible if you have 1 dataset and then you dynamically build up your SQL query. Set up a variable for the columns you want to return based on all the selected comboBoxes.
Use 1 method for all your after update event on the comboBoxes to make it easier and more maintainable.
In terms of mapping the dynamics columns to the dropdowns, I don't work with Winform so I'm not sure but hope this can help a bit.
You can use the for loop to iterate the values you have retrieved and append the combo box value. Example:
comboBox.Items.Clear(); // <-- Declare this at initialization of the page or whatever scenario you have
private void Check1_CheckedChanged(object sender, EventArgs e)
{
if (Check1.CheckState == CheckState.Checked)
{
// SQL Server connection
SqlConnection conn = new SqlConnection(#"Server = Server; Database = DB; Integrated Security = True");
DataSet ds = new DataSet();
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT [Column1] FROM [DB].[dbo].[Table1] WHERE [Column2] = 50", conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
// Using loop to iterate the values and append the combo box
for(int i=0;i<da.Rows.Count;i++)
{
combo1.Items.Add(da[i]["Column1"].ToString());
combo1.Items[combo1.Itemx.Count-1].Text=da[i]["Column1"].ToString();
combo1.Items[combo1.Itemx.Count-1].Value=da[i]["Column1"].ToString();
}
}
catch (Exception ex)
{
//Exception Message
}
finally
{
conn.Close();
conn.Dispose();
}
}
if (Check1.CheckState == CheckState.Unchecked)
{
combo1.DataSource = null;
}
This is just an example, hope you can get the idea
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();
Listbox does not show data. Verified data is in database and I am not getting an
error. Not sure where/what is wrong. Thanks in advance. My code is attached.
private void UpDateList()
{
// add data connection and fill data set.
SqlConnection conn = new SqlConnection(dataSource);
DataTable dt = new DataTable();
string sqlString = "select * from Suppliers";
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
cmd.Connection = conn;
conn.Open();
cmd.CommandText = sqlString;
da.Fill(ds);
conn.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conn.Close();
}
foreach(DataRow dRow in ds.Tables[0].Rows)
{
ArrayList values = new ArrayList();
foreach(object value in dRow.ItemArray)
{
values.Add(value);
_Suppliers.Add(values);
}
}
lstSuppliers.DataSource = _Suppliers;
lstSuppliers.Update();
}
It's kinda pointless to enumerate one bindable data collection and transfer data into another bindable collection so it can be bound. Just have your list use the default view of the datatable that already holds the data (allows sorting, filtering etc)
E.g.
LstSuppliers.DataSource = ds.Tables[0].DefaultView;
LstSuppliers.DisplayMember = "column name goes here of what to show eg SupplierName";
LstSuppliers.ValueMember = "column whose value to use for lstSuppliers.SelectedValue e.g. supplierId";
And then for example, not required but an example possibility:
ds.Tables[0].DefaultView.Sort = "[SupplierName] ASC";
Iam using a datatable to fetch table values from mysql DB.
My codes
public static DataTable mydealdetails()
{
try
{
string connString = "Server=localhost;database=mytable;uid=root;password=Mytable";
string query = "SELECT * FROM `mytable`.`mydealdetails`";
MySqlDataAdapter ma = new MySqlDataAdapter(query, connString);
DataSet DS = new DataSet();
ma.Fill(DS);
return DS.Tables[0];
}
catch (MySqlException e)
{
throw new Exception(e.Message);
}
}
And iam also using this methode
var expression = "MovieMasterId = '"+mouvieid+"'";
DataRow[] foundRows = allmydeals.Select(expression);
I can get two rows count here,but i want to know how can i get each column values by using this methode
I have two Access tables, namely Projects, including the rows of projectTitle and partyID, and ProjectParty, including the rows of title and ID.
private void btnSearch_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=HesabKetab.accdb;Persist Security Info=False;";
//search in the database
OleDbCommand oleCmd = new OleDbCommand();
oleCmd.Connection = conn;
if (radioBtnByTitle.Checked)
{
oleCmd.CommandText = "SELECT * FROM Projects WHERE projectTitle=#projectTitle";
oleCmd.Parameters.AddWithValue("#projectTitle", txtProjectTitle.Text);
}
else if (radioBtnByParty.Checked)
{
oleCmd.CommandText = "SELECT * FROM Projects WHERE partyID=#partyID";
oleCmd.Parameters.AddWithValue("#partyID", comboParty.SelectedValue.ToString());
}
//execute query
OleDbDataAdapter ole_da = new OleDbDataAdapter(oleCmd);
DataTable dt= new DataTable();
try
{
conn.Open();
ole_da.Fill(dt);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
dataGridViewDisplaySearchResults.DataSource = dt;
conn.Close();
}
In the above code I am trying to retrieve the values of the Projects Access database table. The second if is successful and it loads the queried rows into DataGridView. But the first if (when true) does not return the expected values. In fact, it loads nothing into the DataGridView. I have no idea why the query does not work when I try to do the select based on projectTitle. I tried debugging but I got no clue which parameters were being passed to the select command. Where am I wrong?
instead txtProjectTitle.ToString() in the first condition, isn't it txtProjectTitle.Text