refreshing DataSource Master-Detail XtraGrid - c#

i have this code that create Master-Detail XtraGrid at runtime
public partial class FRM_Reserved : DevExpress.XtraEditors.XtraForm
{
DataTable Table1 = new DataTable("Table1");
DataTable Table2 = new DataTable("Table2");
DataSet dataSet = new DataSet();
public FRM_Reserved()
{
InitializeComponent();
Table1 = ord.Get_Orders();
Table2 = ord.Get_Order_Res();
dataSet.Tables.Add(Table1);
dataSet.Tables.Add(Table2);
dataSet.Relations.Add("OrderDetails",
dataSet.Tables["Table1"].Columns["Bon N"],
dataSet.Tables["Table2"].Columns["Bon N"]);
gridControl3.DataSource = dataSet.Tables["Table1"];
}
I want to refreshing DataSource on a click of button so I added this code
private void btnRefresh_Click(object sender, EventArgs e)
{
Table1 = ord.Get_Orders();
Table2 = ord.Get_Order_Res();
dataSet.Tables.Add(Table1);
dataSet.Tables.Add(Table2);
gridControl3.DataSource = dataSet.Tables["Table1"];
gridControl3.ForceInitialize();
}
but the code does not work ,can you help me please.

Try below code. Hope it works
private void btnRefresh_Click(object sender, EventArgs e)
{
gridControl3.DataSource=null;
gridControl3.Items.Clear();
Table1 = ord.Get_Orders();
Table2 = ord.Get_Order_Res();
dataSet.Tables.Add(Table1);
dataSet.Tables.Add(Table2);
gridControl3.DataSource = dataSet.Tables["Table1"];
gridControl3.ForceInitialize();
}

the problem was in the name of the tables it change every time
dataSet.Tables[(Table1.TableName)]
dataSet.Tables[(Table2.TableName)]
so I made this changes
private void simpleButton1_Click(object sender, EventArgs e)
{
dataSet.Relations.Clear();
dataSet.Tables["Table2"].Clear();
dataSet.Tables["Table1"].Clear();
Table1 = ord.Get_Orders();
Table2 = ord.Get_Order_Res();
dataSet.Tables.Add(Table1);
dataSet.Tables.Add(Table2);
dataSet.Relations.Add("OrderDetails",
dataSet.Tables[(Table1.TableName)].Columns["Bon N"],
dataSet.Tables[(Table2.TableName)].Columns["Bon N"]);
gridControl3.DataSource = dataSet.Tables[(Table1.TableName)];
gridControl3.ForceInitialize();
}
Thanks for helping me

Use the following code
gridControl3.DataSource = dataSet.Tables["Table1"];
gridControl3.RefreshDataSource();
Try this one
private void button1_Click(object sender, EventArgs e)
{
var ds = new DataSet();
var dt1 = GetTable1Data();
var dt2 = GetTable2Data();
ds.Tables.Add(dt1);
ds.Tables.Add(dt2);
ds.Relations.Add("RelationTable",
ds.Tables["Table1"].Columns["col1"],
ds.Tables["Table2"].Columns["col1"]);
gridControl1.DataSource = ds.Tables["Table1"];
gridControl1.RefreshDataSource();
}
private DataTable GetTable1Data()
{
using (var conn = new SqlConnection("Conneciton string goes here"))
{
conn.Open();
using (var cmd = new SqlCommand("Stored procedure name goes here", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
var dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
}
private DataTable GetTable2Data()
{
using (var conn = new SqlConnection("Conneciton string goes here"))
{
conn.Open();
const string sql = "SELECT * FROM Table2";
using (var cmd = new SqlCommand(sql, conn))
{
var dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
}

Related

How can I search a listbox items depending on a variable?

I am new to c# and trying to search a listbox as following :
First i have this :
public partial class FrmCodes : Form
{
...
SqlConnection Cn = new SqlConnection(#"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
SqlCommand cmd;
SqlDataReader DataRead;
...
public FrmCodes()
{
InitializeComponent();
cmd = new SqlCommand("Select Item from Items", Cn);
Cn.Open();
DataRead = cmd.ExecuteReader();
while (DataRead.Read())
{
ListItems.Items.Add(DataRead["Item"].ToString());
}
DataRead.Close();
Cn.Close();
}
And tried to do this :
private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.Items.Clear();
while (DataRead.Read())
{
string str = DataRead["Item"].ToString();
string srch = txtSrch.Text;
if (str.Contains(srch))
{
ListItems.Items.Add(str);
}
}
}
It did not work , I tried to make a new sql select query that get data depending on txtSrch.Text but got nothing either .
Thanks in advance.
Edit#1
This is the query i mentioned before :
private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.Items.Clear();
SqlConnection Cn2 = new SqlConnection(#"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
Cn2.Open();
string srch = txtSrch.Text;
using (SqlDataAdapter a2 = new SqlDataAdapter("Select Item from Items WHERE Item LIKE '%" + srch + "%'", Cn2))
{
var t2 = new DataTable();
a2.Fill(t2);
ListItems.DisplayMember = "Item";
ListItems.ValueMember = "Code";
ListItems.DataSource = t2;
}
}
This did not affect the items in the listbox nothing happens on txtSrch Change .
Another solution using Dataview thanks to #Trevor
public partial class FrmCodes : Form
{
...
SqlConnection Cn = new SqlConnection(#"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
SqlDataAdapter da;
DataTable dt = new DataTable();
...
public FrmCodes()
{
InitializeComponent();
da = new SqlDataAdapter("Select Item from Items", Cn);
da.Fill(dt);
DataView dv = new DataView(dt);
ListItems.DataSource = dv;
ListItems.DisplayMember = "Item";
}
Textbox change :
private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.DataSource = null;
DataView dv = new DataView(dt);
string srch = txtSrch.Text;
dv.RowFilter = string.Format("Item Like '%{0}%'", srch);
ListItems.DataSource = dv;
ListItems.DisplayMember = "Item";
}
Thanks.
Basedon #Olivier Jacot-Descombes’ comments, this worked for me:
private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.DataSource = null;
SqlConnection Cn2 = new SqlConnection(#"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
Cn2.Open();
string srch = txtSrch.Text;
using (SqlDataAdapter a2 = new SqlDataAdapter("Select Item from Items WHERE Item LIKE '%" + srch + "%'", Cn2))
{
var t2 = new DataTable();
a2.Fill(t2);
ListItems.DisplayMember = "Item";
ListItems.ValueMember = "Code";
ListItems.DataSource = t2;
}
}

Exactly this is the error: Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

This is the Error being Displayed when the Program is being Run . . .
Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
private void searchClassSectionSchedule_Load(object sender, EventArgs e)
{
comboBox1.DataSource = CSData();
comboBox1.DisplayMember = "ClassSection";
comboBox1.ValueMember = "csec_id";
comboBox1.SelectedIndex = -1;
}
DataTable dt = new DataTable();
//Data of ClassSection is Taken in ComboBox2 from Table "Class_Section" with the help of Stored Procedure (CSEC_View_Data)
private DataTable CSData()
{
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand("CSEC_View_Data", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
SqlDataReader r = cmd.ExecuteReader();
dt.Load(r);
}
}
return dt;
}
private void button2_Click(object sender, EventArgs e)
{
button1.Enabled = true;
while (dataGridView1.RowCount > 1)
{
dataGridView1.Rows.RemoveAt(0);
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
dt = VeiwClassSectionTime();
dataGridView1.DataSource = dt;
button1.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private DataTable VeiwClassSectionTime()
{
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand("CSEC_Time_Display", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("csec_id", comboBox1.SelectedValue);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
dt.Load(reader);
}
}
return dt;
}
}
This Stored Procedure is used for Displaying data in gridVeiw1 and i think it has Error but where it is and how it will be Resolved i dont know . . .
ALTER PROCEDURE [dbo].[CSEC_Time_Display]
(
#csec_id NVARCHAR(50)
)
AS
BEGIN
SELECT
ct.[ct_id]
,ct.[week_day]
,CONVERT(varchar(5), ct.[ct_start],108 ) AS 'ct_start'
,CONVERT(varchar(5), ct.[ct_end],108 ) AS 'ct_end'
,ct.[sub_code]
,ct.[t_id]
FROM [Attendance].[dbo].[ClassTimmings] ct
WHERE ct.[csec_id] = #csec_id
END
Also This is another Stored Procedure :
This is used for sending data in ComboBox1 and is Perfectly Working when Project is being Run
ALTER PROCEDURE [dbo].[CSEC_View_Data]
AS
BEGIN
SELECT
s.[csec_id]
,c.[c_program]+'-'+c.[c_semester]+' '+s.[csec_section] AS 'ClassSection'
FROM [Attendance].[dbo].[Class_Section] s
INNER JOIN [dbo].[Class] c ON s.[c_id] = c.[c_id]
END
I have Changed my Code to the following and Got the Perfect Result
private void searchClassSectionSchedule_Load(object sender, EventArgs e)
{
comboBox1.DataSource = CSData();
comboBox1.DisplayMember = "ClassSection";
comboBox1.ValueMember = "csec_id";
comboBox1.SelectedIndex = -1;
}
//Data of ClassSection is Taken in ComboBox2 from Table "Class_Section" with the help of Stored Procedure (CSEC_View_Data)
private DataTable CSData()
{
DataTable dt = new DataTable();
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand("CSEC_View_Data", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
SqlDataReader r = cmd.ExecuteReader();
dt.Load(r);
}
}
return dt;
}
private void button2_Click(object sender, EventArgs e)
{
button1.Enabled = true;
while (dataGridView1.RowCount > 1)
{
dataGridView1.Rows.RemoveAt(0);
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
dt = VeiwClassSectionTime();
dataGridView1.DataSource = dt;
button1.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private DataTable VeiwClassSectionTime()
{
DataTable dt = new DataTable();
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand("CSEC_Time_Display", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("csec_id", comboBox1.SelectedValue);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
dt.Load(reader);
}
}
return dt;
}
}

How to save changes to DataView to Database on button click?

I'm new to Asp.net and I'm trying to figure out how to update a value in a SqlDataSource programmatically. Here's my button click listener:
protected void ApproveLoanButton_Click(object sender, EventArgs e)
{
DataView dv = (DataView)DetailsSqlDataSource.Select(DataSourceSelectArguments.Empty);
dv.AllowEdit = true;
using (var dt = dv.ToTable())
{
var oldValue = dt.Rows[0]["IsApproved"].ToString();
dt.Rows[0]["IsApproved"] = true;
var newValue = dt.Rows[0]["IsApproved"].ToString();
dt.AcceptChanges();
GridView1.DataBind();
DetailsView1.DataBind();
}
}
The oldValue is false and the newValue is true so I am changing the value but it doesn't save to the database when I call AcceptChanges(). What am I doing wrong here? I've already spent hours on this. Thanks for your help!
I do not have what your DetailsSqlDataSource is, or what your database structure is like, but you would obviously need to write a few Save and Read methods.
If you did that, you would have something like this:
protected void ApproveLoanButton_Click(object sender, EventArgs e)
{
DataView dv = (DataView)DetailsSqlDataSource.Select(DataSourceSelectArguments.Empty);
dv.AllowEdit = true;
using (var dt = dv.ToTable())
{
var oldValue = dt.Rows[0]["IsApproved"].ToString();
if (-1 < SaveApproved((int)dt.Rows[0]["ID"], true))
{
dt.Rows[0]["IsApproved"] = true;
var newValue = dt.Rows[0]["IsApproved"].ToString();
dt.AcceptChanges();
DetailsSqlDataSource = GetTable();
GridView1.DataBind();
DetailsView1.DataBind();
}
}
}
You will need to modify these to work, but here is a sample:
private const string SQL_CONNECTION = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
private DataTable GetTable()
{
var table = new DataTable();
using (var con = new System.Data.SqlClient.SqlConnection(SQL_CONNECTION))
{
con.Open();
using (var cmd = new System.Data.SqlClient.SqlCommand("SELECT * FROM MyTable;", con))
{
table.Load(cmd.ExecuteReader());
}
}
return table;
}
private int SaveApproved(int rowID, bool approved)
{
using (var con = new System.Data.SqlClient.SqlConnection(SQL_CONNECTION))
{
con.Open();
using (var cmd = new System.Data.SqlClient.SqlCommand("UPDATE MyTable SET IsApproved=#IsApproved WHERE ID=#ID;", con))
{
cmd.Parameters.Add("#IsApproved", SqlDbType.Bit).Value = approved;
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = rowID;
return cmd.ExecuteNonQuery();
}
}
}

Display date selected in one form to another form

I want to display the date which is selected in another form using monthCalender control..
Here is my code..
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
ActivityScheduler frm1 = new ActivityScheduler();
frm1.Show();
}
private void ActivityScheduler_Load(object sender, EventArgs e)
{
if (con.State == ConnectionState.Open) { con.Close(); }
con.Open();
RemainderPopUp frm = new RemainderPopUp();
string s = "select * from [Activity_Scheduler]";
SqlCommand sCmd = new SqlCommand(s, con);
SqlDataAdapter da = new SqlDataAdapter(sCmd);
DataSet ds = new DataSet();
da.Fill(ds, "[Activity_Scheduler]");
datagridActivityScheduler.DataSource = ds.Tables[0];
datagridActivityScheduler.AllowUserToAddRows = true;
DataTable dt = new DataTable();
dt = ds.Tables["Activity_Scheduler"];
if (dt == null)
{
datagridActivityScheduler.Rows[0].Cells[3].Value = frm.monthCalendar1.SelectionRange.Start.ToShortDateString();
MessageBox.Show(datagridActivityScheduler.Rows[0].Cells[3].Value.ToString());
}
con.Close();
}
It is displaying the correct value in messagebox..but the value is not displaying in datagridview...
Plz anybody help me out..
Try Following Code :
form_load()
{
private string myDate="1999/12/12";
// Declare a Date property of type string:
public string Name
{
get
{
return myDate;
}
set
{
myName = value;
}
}
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
ActivityScheduler frm1 = new ActivityScheduler();
ActivityScheduler.myDate = frm.monthCalendar1.SelectionRange.Start.ToShortDateString()
frm1.Show();
}
Now you can get date on other form as :
string myDate = frm1.myDate();
Let me know if any queries.

update Cascading combobox problem C#

i have a simple question
i have a form which contain two related combo boxes but i have problem in updating the second dropdown content
this is the code
private void DiaryForm_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'expensesDataSet.Item' table. You can move, or remove it, as needed.
// this.itemTableAdapter.Fill(this.expensesDataSet.Item);
using (OleDbConnection con = dbconn.dbconnection())
{
ds1 = new ExpensesDataSet();
string sql = "SELECT * From DiaryView";
da = new System.Data.OleDb.OleDbDataAdapter(sql, con);
da.Fill(ds1, "DiaryView");
NavigateRecords();
MaxRows = ds1.Tables["DiaryView"].Rows.Count;
//fill category combobox
string sqlcat = "SELECT * From Category";
catda = new System.Data.OleDb.OleDbDataAdapter(sqlcat, con);
catda.Fill(ds1, "Category");
catda.Update(ds1, "Category");
comboBox2.DataSource=ds1.Tables["Category"];
comboBox2.DisplayMember = "cat_name";
comboBox2.ValueMember="cat_id";
//comboBox1.Enabled = false;
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
using (OleDbConnection con = dbconn.dbconnection())
{
if (comboBox2.Items.Count > 0)
{
{
string cat = comboBox2.SelectedValue.ToString();
comboBox1.Enabled = true;
int catid = int.Parse(comboBox2.SelectedValue.ToString());
string sqlitem = "SELECT * From Item where cat_id = " + catid;
catda = new System.Data.OleDb.OleDbDataAdapter(sqlitem, con);
this.itemBindingSource.EndEdit();
catda.Fill(ds1, "Item");
catda.Update(ds1, "Item");
comboBox1.DataSource = ds1.Tables["Item"];
comboBox1.DisplayMember = "item_name";
comboBox1.ValueMember = "item_id";
}
}
}
}
there is two tables:
category(cat_id,cat_name)
item(item_id,item_name,cat_id)
what can i do??
plz help :)
If you want to clear the combobox, just do:
combobox1.Items.Clear();
It's as easy as that.

Categories