I am developing a windows forms application. I use DataGridView and data binding with LINQ to SQL. It's working. It binds the whole data.
I need some fields instead of whole table data, for example:
The Customers table contains five fields (name, address, mobile, email, age).
I use the code below to get whole data.
private void AssignLocation_Load(object sender, EventArgs e)
{
// Get Datacontext object to connect with data source
SmartxBillingSystemDataContext dc = new SmartxBillingSystemDataContext();
// create table object
Customer customer = new Customer();
var allcustomers = from c in dc.GetTable<Customer>() select c;
// bind to datagrid
customerBindingSource.DataSource = allcustomers;
// now assign binding source to data grid view
dataGridView1.DataSource = customerBindingSource;
}
Now I just need some fields, e.g. Name and Address.
Additionally, I need to add a button in each row like so:
| A Name | An Address | Button |
| Another Name | Fake Address | Button |
How can I achieve this? Please help.
For click event I use below code
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
popUpLocationWindow();
}
private void popUpLocationWindow()
{
MessageBox.Show("I am clicked");
}
But this code not works.
You can create your own class:
public class MyCustomer
{
public string Name { get; set; }
public string Address { get; set; }
}
and select like this:
var allMycustomers = from c in dc.GetTable<Customer>() select new MyCustomer { Name = c.Name, Address = c.Address };
customerBindingSource.DataSource = allMycustomers;
for button:
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
btn.HeaderText = "Button";
btn.Text = "Click Me!";
btn.Name = "btn";
dataGridView1.Columns.Add(btn);
btn.UseColumnTextForButtonValue = true;
Update for button click event you can use dataGridView1_CellClick event..
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 2)
{
MessageBox.Show((e.RowIndex+1) + " Row " + (e.ColumnIndex+1) + " Column button clicked ");
}
}
Related
I'm working on a school project with C# Winforms where I have to create a vehicle sales invoice and ope a new form with information about the vehicle that was selected from a combobox. How do I get the Vehicle object or its properties based on the SelectedItem in the combobox?
The Vehicle objects are in a list which is bound to a BindingSource which is bound to the combobox.
I was able to pass static strings through to a new form in another component of this assignment, but I can't figure out how to retrieve the object information.
My list of vehicles bound to the combobox. DataRetriever is a class we were given to provide us with the Vehicle objects. They have auto-implemented properties (make, model, id, colour, etc.)
List<Vehicle> vehicles = DataRetriever.GetVehicles();
BindingSource vehiclesBindingSource = new BindingSource();
vehiclesBindingSource.DataSource = vehicles;
this.cboVehicle.DataSource = vehiclesBindingSource;
this.cboVehicle.DisplayMember = "stockID";
this.cboVehicle.ValueMember = "basePrice";
I want to be able to pass information to this form and display information about the selected vehicle with labels.
private void vehicleInformationToolStripMenuItem_Click(object sender, EventArgs e)
{
VehicleInformation vehicleInformation = new VehicleInformation();
vehicleInformation.Show();
}
On Form_Load
List<VecDetails> lstMasterDetails = new List<VecDetails>();
private void frmBarcode_Load(object sender, EventArgs e)
{
VechicleDetails();
BindingSource vehiclesBindingSource = new BindingSource();
vehiclesBindingSource.DataSource = lstMasterDetails;
this.comboBox1.DataSource = vehiclesBindingSource;
this.comboBox1.DisplayMember = "stockID";
this.comboBox1.ValueMember = "basePrice";
}
In VechicleDetails() Method i'm just generating the sample value so i can i them to ComboBox
private void VechicleDetails()
{
//Sample Method to Generate Some value and
//load it to List<VecDetails> and then to ComboBox
for (int n = 0; n < 10; n++)
{
VecDetails ve = new VecDetails();
ve.stockID = "Stock ID " + (n + 1).ToString();
ve.basePrice = "Base Price " + (n + 1).ToString();
lstMasterDetails.Add(ve);
}
}
Now on comboBox1_SelectedIndexChanged event i'm getting the value of the item selected
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
string strStockId = comboBox1.Text.ToString();
string strBasePrice = (comboBox1.SelectedItem as dynamic).basePrice;
label1.Text = strStockId + " - " + strBasePrice;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I am attempting to write code that will display data in a datagridview based off of the size of car selected in a combo box. When this code initially runs, it defaults to economy sized, and displays the correct information in the datagridview. However, when a different size is selected in the combo box, the text boxes update correctly while the datagridview remains the same. What can I do to make it update every time the combo box is changed? I thought the code in "private void cboSize_selectionChangeCommitted()" would accomplish this, but there was no change in the output.
namespace carForm
{
public partial class Form1 : Form
{
_Cars_1_DataSet cDataSet;
BindingSource sizeBindingSource;
BindingSource vehicleBindingSource;
CarsDataClass clsCarsData;
Boolean gridInitialized;
public Form1()
{
InitializeComponent();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the '_Cars_1_DataSet.Reservations' table. You can move, or remove it, as needed.
this.reservationsTableAdapter.Fill(this._Cars_1_DataSet.Reservations);
// TODO: This line of code loads data into the '_Cars_1_DataSet.Vehicle' table. You can move, or remove it, as needed.
this.vehicleTableAdapter.Fill(this._Cars_1_DataSet.Vehicle);
// TODO: This line of code loads data into the '_Cars_1_DataSet.CarSize' table. You can move, or remove it, as needed.
this.carSizeTableAdapter.Fill(this._Cars_1_DataSet.CarSize);
clsCarsData = new CarsDataClass();
cDataSet = clsCarsData.GetDataSet();
//Binding source sizes
sizeBindingSource = new BindingSource();
sizeBindingSource.DataSource = cDataSet;
sizeBindingSource.DataMember = "CarSize";
//Binding source vehicles
vehicleBindingSource = new BindingSource();
vehicleBindingSource.DataSource = cDataSet;
vehicleBindingSource.DataMember = "Vehicle";
//Combo box
cboSize.DataSource = sizeBindingSource;
cboSize.DisplayMember = "Size";
cboSize.ValueMember = "SizeCode";
//bind other controls
txtDaily.DataBindings.Add("text", sizeBindingSource, "DailyRate");
txtMileage.DataBindings.Add("text", sizeBindingSource, "MileageRate");
//execute combo box
cboSize_SelectionChangeCommitted(cboSize, e);
}
private void cboSize_SelectionChangeCommitted(object sender, EventArgs e)
{
string carSelected;
carSelected = Convert.ToString(cboSize.SelectedValue);
if (!gridInitialized)
{
dgvVehicles.DataSource = vehicleBindingSource;
gridInitialized = true;
ChangeGridColumns();
}
vehicleBindingSource.Filter = "CarSize = '" + carSelected + "'";
}
private void ChangeGridColumns()
{
//Change column headers
//dgvVehicles.Columns["Inv_ID"].Visible = false;
}
}
}
Try using SelectedIndexChanged event from the events menu after clicking on the combobox in the design view.
This should populate in your code:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Console.WriteLine("test!");
}
In there you can put this logic from your code:
string carSelected;
carSelected = Convert.ToString(cboSize.SelectedValue);
if (!gridInitialized)
{
dgvVehicles.DataSource = vehicleBindingSource;
gridInitialized = true;
ChangeGridColumns();
}
vehicleBindingSource.Filter = "CarSize = '" + carSelected + "'";
Use SelectedIndexChanged instead of SelectionChangeCommitted.
So I'm trying to update a row in a database using the text from a textbox using .net forms.
On pageload I load the value and assign it to the text property of the textbox. Next I allow the user to change the text and click a button to upload, however the value in the database is not changed.
If I change the holter.companyName value to a static string the database updates. Also if I do not assign a companyNameTB.text value at pageloads the update button works as expected.
Any ideas?
protected void Page_Load(object sender, EventArgs e)
{
PortalEntities db = new PortalEntities();
var holterQuery = from holt in db.Holters
where holt.Id == 1
select holt;
Holter holter = holterQuery.Single();
string companyName = holter.CompanyName;
CompanyNameTB.Text = companyName;
}
protected void Button1_Click(object sender, EventArgs e)
{
PortalEntities db = new PortalEntities();
var holterQuery = from holt in db.Holters
where holt.Id == 1
select holt;
Holter holter = holterQuery.Single();
holter.CompanyName = CompanyNameTB.Text;
holter.Id = 1;
db.SaveChanges();
}
It looks like the Page_Load method is overwriting the textbox when the form is submitted. Put it inside of a conditional statement in order to check to see if the request is a post back, like so:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostback)
{
PortalEntities db = new PortalEntities();
var holterQuery = from holt in db.Holters
where holt.Id == 1
select holt;
Holter holter = holterQuery.Single();
string companyName = holter.CompanyName;
CompanyNameTB.Text = companyName;
}
}
This should allow the textbox to be populated from the database when the page is initially loaded, but then when the user submits the form that section of code should be skipped so that the new value in the textbox doesn't get overwritten.
Do this in the Page_Load method, otherwise the value in the textBox is refreshed to the original one at any page request (so the post back request too)
if(!Page.IsPostBack)
{
PortalEntities db = new PortalEntities();
var holterQuery = from holt in db.Holters
where holt.Id == 1
select holt;
Holter holter = holterQuery.Single();
string companyName = holter.CompanyName;
CompanyNameTB.Text = companyName;
}
And you don't need this line is the Button1_Click method
holter.Id = 1;
I have a local database (SQL) with two tables Contact and Address. The Contact table contains 5 address fields (Address1, Address2,...) that are foreign keys linked to the primary key of the Address table. What ik want to do is when I select (for instance using a combobox) a contacts name, view all addresses linked to the contact. I'm a complete noob in C# programming and have no idee to make the above happen. Can anyone show me how I can view the addresses by selecting the contacts name?
EDIT (after trying some coding):
Ok, this is how far I get. I have my two forms. FORM 1 has a datagridview, viewing a button, firstname and lastname. Entering firstname and lastname in textBox1 and textBox2 and pressing button1 results in a list of records that match firstname OR lastname.
Clicking the button in column 0 shows the contactsheet. I've tried to pass firstname and lastname to textboxes tboFNAME and tboLNAME, but nothing appears in these textboxes.
In the next stage I would like to pass the address ID's (foreign keys) to the contactsheet and subsequently load the linked data in the corresponding textboxes.
FORM 1:
public partial class Form1 : Form
{
//SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\xxx\Documents\Visual Studio 2013\Projects\xxx\xxx\xxx.mdf;Integrated Security=True;Connect Timeout=30");
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\xxx\Documents\Visual Studio 2013\Projects\xxx\xxx\xxx.mdf;Integrated Security=True;Connect Timeout=30");
dataGridView1.Visible = true;
int varCount;
varCount = 0;
int i = 0;
for (i = 1 ; i < dataGridView1.Rows.Count-1; i++)
{
if (!dataGridView1.Rows[i].IsNewRow)
{
if (dataGridView1[3, i].Value.ToString() == textBox1.Text
|| dataGridView1[5, i].Value.ToString() == textBox2.Text
)
{
dataGridView1.Rows[i].Visible = true;
varCount += 1;
Console.WriteLine(varCount);
int RHeight = dataGridView1.RowTemplate.Height;
int gridHeight = (varCount * RHeight) + RHeight;
dataGridView1.Height = gridHeight;
}
else
{
dataGridView1.Rows[i].Visible = false;
}
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'sAFIREDBDataSet1.contactdata' table. You can move, or remove it, as needed.
this.contactdataTableAdapter1.Fill(this.sAFIREDBDataSet1.contactdata);
this.contactdataTableAdapter.Fill(this.sAFIREDBDataSet.contactdata);
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var senderGrid = (DataGridView)sender;
String fnameRef = (String)dataGridView1.Rows[e.RowIndex].Cells[3].Value;
String lnameRef = (String)dataGridView1.Rows[e.RowIndex].Cells[5].Value;
if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn &&
e.RowIndex >= 0)
{
Contactsheet myForm = new Contactsheet();
myForm.getFNAME = fnameRef;
myForm.getLNAME = lnameRef;
myForm.Show();
}
}
}
FORM 2 (Contactsheet)
public partial class Contactsheet : Form
{
public Contactsheet()
{
InitializeComponent();
}
public string getFNAME;
public string getLNAME;
private void Contactsheet_Load(object sender, EventArgs e)
{
tboFNAME.Text = getFNAME;
tboLNAME.Text = getLNAME;
}
}
First of all you must connect to your SQL db as you probably know.
I think that the simplest way will be to use Entity Framework (version 5 or 6).
Create new edmx file, new connection to your database and import your tables.
Try to write some code. May be you figured it out. If not then ask more accurate question with examples of your tries:)
I have XtraTabControl with two pages, both of them has one LookUpEdit,
when page load which on the secondpage does not work,
void Frm1_Load(object sender, EventArgs e)
{
lookUpEditA.Properties.DataSource = datasource. . . . .
lookUpEditA.Properties.ValueMember = "ID";
lookUpEditA.Properties.DisplayMember = "xxxx";
lookUpEditA.Properties.PopulateColumns();
lookUpEditA.Properties.Columns["ID"].Visible = false;
lookUpEditB.Properties.DataSource = datasource. . . . .
lookUpEditB.Properties.ValueMember = "ID";
lookUpEditB.Properties.DisplayMember = "xxxx";
lookUpEditB.Properties.PopulateColumns();
lookUpEditB.Properties.Columns["ID"].Visible = false;
}
I can see the issue only with setting visibility of 'ID' column on second LookUpEdit.
The reason of this issue is that the LookUpEdit can't operate with datasource representation (perform populating columns, operating with column's visibility and etc.) until it's handle been created. The second LookUpEdit will create it's handle only when the second tab page has been shown.
To avoid the issue you can use the following approach:
if(!lookUpEditB.IsHandleCreated)
lookUpEditB.HandleCreated += lookUpEditB_HandleCreated;
else InitLookUpEditDataSource();
//...
void lookUpEditB_HandleCreated(object sender, EventArgs e) {
lookUpEditB.HandleCreated -= lookUpEditB_HandleCreated;
InitLookUpEditDataSource();
}
void InitLookUpEditDataSource() {
lookUpEditB.Properties.DataSource = this.categoriesBindingSource;
lookUpEditB.Properties.DisplayMember = "CategoryName";
lookUpEditB.Properties.ValueMember = "CategoryID";
lookUpEditB.Properties.PopulateColumns();
lookUpEditB.Properties.Columns["CategoryID"].Visible = false;
}
As #DmitryG said, you can not use lookUpEditB.Properties.PopulateColumns() statement until control's UI handlers are not created.
As per my understanding these are created only when the second tab page shown. Except creating conditional statement to create handlers etc, you can use the XtraTabControl.SelectedPageChanged Event where you can bind the data source of the lookUpEditB by checking condition that XtraTabControl.SelectedTabPage Property is set with Page2 which contain the lookUpEditB.
Check the tested Code Snippet below:
public partial class TabControlTest : Form
{
List<Category> dataSource = new List<Category>();
public TabControlTest()
{
InitializeComponent();
for (int i = 0; i < 10; i++)
{
dataSource.Add(new Category { ID = i + 1, Name = "Category" + (i + 1) });
}
}
private void TabControlTest_Load(object sender, EventArgs e)
{
lookUpEditA.Properties.DataSource = dataSource;
lookUpEditA.Properties.ValueMember = "ID";
lookUpEditA.Properties.DisplayMember = "Name";
lookUpEditA.Properties.PopulateColumns();
lookUpEditA.Properties.Columns["ID"].Visible = false;
}
private void xtraTabControl1_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
{
if (xtraTabControl1.SelectedTabPage == xtraTabPage2)
{
lookUpEditB.Properties.DataSource = dataSource;
lookUpEditB.Properties.ValueMember = "ID";
lookUpEditB.Properties.DisplayMember = "Name";
lookUpEditB.Properties.PopulateColumns();
lookUpEditB.Properties.Columns["ID"].Visible = false;
}
}
}
Hope this help.