I have 1 WinForm with 2 Combo boxes, first one is filled with Employee names, and the second one is supposed to be filled with tasks that are affected to every employee listed in the first combo. But could not get the following code to run for the second combo:
private void Form1_Load(object sender, EventArgs e)
{
using (LINQtoEntitiesEntities MyEntities = new LINQtoEntitiesEntities())
{
ObjectQuery<Employee> Emp = MyEntities.Employee;
comboBox1.DataSource = (from u in Emp select new { u.ID, u.LastName }).ToList();
comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "LastName";
}
}
private void comboBox1_TextChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex.ToString() == "0") return;
using (LINQtoEntitiesEntities MyEntities = new LINQtoEntitiesEntities())
{
label1.Text = comboBox1.SelectedValue.ToString();
ObjectQuery<Tasks> Tsk = MyEntities.Tasks;
comboBox2.DataSource = (from t in Tsk where t.EmloyeeID.ToString() == comboBox1.SelectedValue.ToString() select new { t.ID, t.TaskName }).ToList();
comboBox2.ValueMember = "ID";
comboBox2.DisplayMember = "TaskName";
}
}
Could fill normally ComboBox1, but not ComboBox2, and it would be great if first line of ComboBox1 is blank.
You want to handle combobox1's SelectedIndexChanged event instead of the TextChanged event.
To insert an empty value, try this:
// replace the -1 with an appropriate value that matches the type of u.ID
(from u in Emp select new { u.ID, u.LastName }).ToList().Insert(0, new { -1, string.Empty });
Related
I have a combobox that gets populated from a database table. When the combobox is diplayed in the window it has the StationName, but it also has a "hidden" value for a StationId. Here is how I get the combobox to display the choices:
StationBox.ItemsSource = dc.WasteTrackerStations;
How can I get to that StationId property to use that in a seperate query to populate a datagrid? This is the code for my SelectionChanged event:
private void StationBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var miquery = from mi in dc.WasteTrackerDBs
where mi.StationId == [this value needs to be StationId from combobox selection]
select new
{
mi.MenuItem,
mi.LeftOver,
mi.Par,
mi.UoM,
mi.StationId
};
EWDataGrid.ItemsSource = miquery;
}
ComboBox has SelectedItem property. It will be an element of dc.WasteTrackerStations collection (or null). Cast it to concrete type and all properties will be accessible:
private void StationBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var item = StationBox.SelectedItem as WasteTrackerStation;
if (item == null) return;
var selectedStationId = item.StationId;
var miquery = from mi in dc.WasteTrackerDBs
where mi.StationId == selectedStationId
select new
{
mi.MenuItem,
mi.LeftOver,
mi.Par,
mi.UoM,
mi.StationId
};
EWDataGrid.ItemsSource = miquery;
}
i'am actually trying to get the new values of the new added row from my grid control (devexpress) thant i set "AllowAddRows" to true;
i can get the updated one like this
Object row = ListeQual.GetRow(ListeQual.FocusedRowHandle);
but i can get the new values in add event for insert
Try this :
private void ListeQual_ValidateRow(object sender, ValidateRowEventArgs e)
{
GridView view = sender as GridView;
if (view.IsNewItemRow(e.RowHandle))
{
DataRow row = view.GetDataRow(e.RowHandle);
}
}
You can create a button how allow to add new row :
private void AddNewRow_Click(object sender, EventArgs e)
{
// (ListeQual.MainView as DevExpress.XtraGrid.Views.Grid.GridView).AddNewRow();
ListeQual.AddNewRow();
}
And a create a methode how you can pass the new row as parameter for saving in datatbase :
private int insertData(DataRow dr)
{
string connectionString = "your connection string here";
int nb = 0;
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO Data (Col1, Col2, Col3) VALUES (#col1, #col2, #col3)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#col1", dr[0]);
cmd.Parameters.AddWithValue("#col2", dr[1]);
cmd.Parameters.AddWithValue("#col3", dr[2]);
connection.Open();
nb= cmd.ExecuteNonQuery();
}
return nb;
}
Finally you can handle the event ValidateRow :
private void ListeQual_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
{
GridView view = ListeQual as GridView;
if (view.IsNewItemRow(e.RowHandle))
{
DataRow dw = view.GetDataRow(e.RowHandle);
insertData(dw);
}
}
My question was how to get the item or value of a selecteditem out of my datagrid that gets filled by a obc of my view. From te result that i get it seems i need to cast it but all the casts i found from google and here are not working.
Anyone got some tips or solution?
public partial class req: Page
{
DataClasses1DataContext dc = new DataClasses1DataContext();
public requests()
{
InitializeComponent();
//get from Database View
var query = from r in dc.requestViews select r;
this.gridRequest.ItemsSource = new ObservableCollection<requestView>(query);
this.gridRequest.ColumnWidth = 122.7;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
if (gridRequest.SelectedItem == null)
{
MessageBox.Show("Select a Order!");
}
else
{
var qres = (from r in dc.orders where r.id.Equals(gridRequest.SelectedValue) select r).FirstOrDefault();
qres.order_status_id = 3;
dc.SubmitChanges();
MessageBox.Show("Request Accepted");
this.NavigationService.Refresh();
}
}
I have below code in Form2
public void authorisedList()
{
using (myContext v = new myContext())
{
DateTime date = DateTime.Today.AddMonths(-12);
var myList = (from l in v.AuthorisedList
where l.FromDate >= date
select new
{
l.ID,
l.EmpName,
l.StartDate,
l.EndDate,
l.Days,
l.Approved,
l.Confirmed,
}).ToList();
reportViewer1.LocalReport.DataSources.Clear();
ReportDataSource datasource = new ReportDataSource("MyReportsDatasource", myList);
reportViewer1.LocalReport.DataSources.Add(datasource);
string exeFolder = Path.GetDirectoryName(Application.ExecutablePath);
string reportPath = Path.Combine(exeFolder, #"rdlcReports\Authorised List.rdlc");
reportViewer1.LocalReport.ReportPath = reportPath;
reportViewer1.RefreshReport();
}
}
Then in Form1 which is a parent of Form2, i have below code in radiobutton
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
Form2 au = new Form2(this);
au.authorisedList();
}
The problem is that when i check a radioButton control (radioButton1) in Form1, authorisedList() in Form2 seems to be executing but the reportViewer report does not update/change.
Am wondering why.
If your Form2 is already open , then you should get the object of the open form and then call its authorisedList() method. You can use Application.OpenForms property.
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
Form2 au = Application.OpenForms["Form2"] as Form2;
if(au != null)
au.authorisedList();
}
Using Windows Forms, two link labels are created dynamically. When the user clicks on anyone of links labels, one dynamic form is created. In that form I created one data grid, a text box and a button placed dynamically (in that dynamic form). Now I want to access the dynamic data grid in the dynamic button click event. How can I do that?
private void Users_Load(object sender, EventArgs e)
{
da = new SqlDataAdapter("Usp_Get_Employees", con);
ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string somecode = i.ToString() + ds.Tables[0].Rows[i]["eid"].ToString();
LinkLabel lbluser = new LinkLabel();
lbluser.Name = ds.Tables[0].Rows[i]["eid"].ToString();
lbluser.Text = ds.Tables[0].Rows[i]["ename"].ToString();
lbluser.Location = new System.Drawing.Point(40, i * 40);
lbluser.Size = new System.Drawing.Size(50, 30);
Controls.Add(lbluser);
lbluser.Click += new EventHandler(lbluser_Click);
}
}
}
void lbluser_Click(object sender, EventArgs e)
{
LinkLabel lnkClis = (LinkLabel)sender;
Form frm = new Form();
frm.Name = lnkClis.Name;
frm.Text = lnkClis.Text;
frm.Show();
DataGrid dtgrd = new DataGrid();
dtgrd.Location = new System.Drawing.Point(10, 1 * 40);
dtgrd.Name = lnkClis.Name;
names = lnkClis.Name;
TextBox tx = new TextBox();
tx.Location = new System.Drawing.Point(10, 5 * 40);
tx.Size = new Size(80, 30);
tx.Multiline = true;
tx.LostFocus += new EventHandler(tx_LostFocus);
Button btn = new Button();
btn.Location = new System.Drawing.Point(10, 7 * 40);
btn.Size = new System.Drawing.Size(50, 30);
btn.Name = lnkClis.Name;
btn.Click += new EventHandler(btn_Click);
frm.Controls.Add(dtgrd);
frm.Controls.Add(tx);
frm.Controls.Add(btn);
}
// Now I am trying to access the data grid in the btn_click event
void btn_Click(object sender, EventArgs e)
{
Button btsave = (Button)sender;
string eid = btsave.Name;
object grd = btsave.Parent.Controls.Find("dtgrd", true).FirstOrDefault();
((DataGrid)grd).DataSource = ds.Tables[0];
}
Now I am getting an error object set of instances of an object at:
((DataGrid)grd).DataSource = ds.Tables[0];
The exception message you have written:
Now I am getting an error object set of instances of an object at
makes no sense, but it looks like
Object reference not set to an instance of an object
If this is the case, I think the error lays in Find method call. According to documentation:
Searches for controls by their Name property and builds an array of all the controls that match.
In your button click handler you assume that grid is called dtgrd, but while you create a grid you name it like this:
dtgrd.Name = lnkClis.Name;
it will suffice if you change this line to:
dtgrd.Name = "dtgrd";
Having said that, you should consider using an anonymous method for the button click handler. It will eliminate need for calling the Find method in the first place.
void lbluser_Click(object sender, EventArgs e)
{
//...
DataGrid dtgrd = new DataGrid();
//...
Button btn = new Button();
//...
btn.Click += (sender,args)=> dtgrd.DataSource = ds.Tables[0];
Try the following code
public Form1()
{
Form f1 = new Form();
f1.Text = "New Form";
TextBox t1 = new TextBox();
t1.Top = 0;
t1.Name = "t1";
t1.Visible = true;
f1.Controls.Add(t1);
Button b1 = new Button();
b1.Top = 30;
b1.Name = "b1";
b1.Text = "Click";
b1.Click += b1_Click;
f1.Controls.Add(b1);
f1.Show();
}
public void b1_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
object txt = btn.Parent.Controls.Find("t1", false).First();
((TextBox)txt).Text = "Hi, you have clicked me.";
}
I modified Nitesh's code a bit. Just capture the textbox in the click handler using a lambda:
public Form1()
{
Form f1 = new Form();
f1.Text = "New Form";
TextBox t1 = new TextBox();
t1.Top = 0;
t1.Name = "t1";
t1.Visible = true;
f1.Controls.Add(t1);
Button b1 = new Button();
b1.Top = 30;
b1.Name = "b1";
b1.Text = "Click";
b1.Click += (sender, args) => MessageBox.Show("The text is: " + t1.Text);
f1.Controls.Add(b1);
f1.Show();
}
The error you are getting is from the statement (as the grd object is null):
((DataGrid)grd).DataSource = ds.Tables[0];
Since you are trying to catch hold of a dynamic control, it's good have a proper null checks, type checks, and error handling. Something like this:
if(grd != null && grd is DataGrid)
((DataGrid)grd).DataSource = ds.Tables[0];