I am trying to pass selected rows of a datagridview to a second form. Then select items in a second DGV and pass the information into a table at that point. What I was trying to do is pass the rows in the manner below:
Form1:
private void toolStripLabel1_Click(object sender, EventArgs e)
{
int interestsKey;
interestsKey = Convert.ToInt32(interestsKeyTextBox.Text);
DataGridViewSelectedRowCollection rows = interestAddDataGridView.SelectedRows;
frmDupeAdd AddDupeForm = new frmDupeAdd(interestAddDataGridView.SelectedRows);
AddDupeForm.Show();
}
On form 2 I cannot seem to be able to access dgIntRows. Not sure if this is the correct way to do this or if there is a better way.
Form 2:
public frmDupeAdd(DataGridViewSelectedRowCollection selectedRows)
{
InitializeComponent();
DataGridViewSelectedRowCollection dgIntRows = selectedRows;
}
private void btnAddAdds_Click(object sender, EventArgs e)
{
DataGridViewSelectedRowCollection rows = dgCaseInt.SelectedRows;
dgCaseInt.Columns[4].Visible = false;
dgCaseInt.Columns[5].Visible = false;
foreach (DataGridViewRow row in rows)
{
DataClasses1DataContext db = new DataClasses1DataContext();
int interestkeyint = Convert.ToInt16(row.Cells[4].Value);
InterestAdd newinterestadd = new InterestAdd();
newinterestadd.InterestsKey = interestkeyint;
foreach (DataGridViewRow row in dgIntRows)
{
newinterestadd.CaseNumberKey = (string)row.Cells[5].Value; ;
newinterestadd.streetNum = (string)row.Cells[2].Value;
newinterestadd.Direction = (string)row.Cells[2].Value;
newinterestadd.Add1 = (string)row.Cells[3].Value;
newinterestadd.Suffix = (string)row.Cells[4].Value;
newinterestadd.Unit = (string)row.Cells[5].Value;
newinterestadd.City = (string)row.Cells[6].Value;
newinterestadd.State = (string)row.Cells[7].Value;
newinterestadd.Zip = (string)row.Cells[8].Value;
db.InterestAdds.InsertOnSubmit(newinterestadd);
db.SubmitChanges();
}
}
}
instead of
public frmDupeAdd(DataGridViewSelectedRowCollection selectedRows)
{
InitializeComponent();
DataGridViewSelectedRowCollection dgIntRows = selectedRows;
}
use
private DataGridViewSelectedRowCollection dgIntRows = new DataGridViewSelectedRowCollection ()
public frmDupeAdd(DataGridViewSelectedRowCollection selectedRows)
{
InitializeComponent();
dgIntRows = selectedRows;
}
Related
I have a DataGridView (DGV) that is NOT using data binding The data is in a SQLite DB
I have written a method that styles the DataGridView
I can populate the DGV with the id of the records in the DB and two string variables
For testing I have 4 TextBox's on the form when I click on the cells I would like to
retrieve the id to transfer that value to another form to use in SQL search
I have tried a number of methods to get data by clicking on the DGV all three are in the
posted code NO I DO NOT WANT to use data binding
SIDE NOTE I have this code working in a VB.Net application no issues
I am new to C# so the code conversion may be the real issue
SO the question is Using C# How to click on a DGV and retrieve the selected value?
public partial class frmSelect : Form
{
string gv_parentInt = "";
string gv_firstName = "";
string gv_lastName = "";
public frmSelect()
{
InitializeComponent();
}
private void frmSelect_Load(object sender, EventArgs e)
{
StyleDGV();
readFriendsData();
}
// Thried these two methods below NO RESULTS
/* private void dgvPerson_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = dgvPerson.Rows[e.RowIndex];
tbID.Text = row.Cells[0].Value.ToString();
tbFName.Text = row.Cells[1].Value.ToString();
tbLName.Text = row.Cells[2].Value.ToString();
}
}*/
/*public void dgvPerson_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dgvPerson.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
{
tbMessage.Text = dgvPerson.SelectedCells[0].Value.ToString();
}
}*/
public void dgvPerson_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1 || e.ColumnIndex == -1)
{
tbMessage.Text = "Col " + e.ColumnIndex + " ROW " + e.RowIndex;// for testing
tbMessage.Text = "No Clicking Here";
//return;
}
string strFName;
string strLName;
DataGridViewRow row = dgvPerson.Rows[e.RowIndex];
strFName = dgvPerson.CurrentRow.Cells[0].Value.ToString();
if (strFName != " ")
{
if (strFName == " ")
return;
int intId = System.Convert.ToInt32(row.Cells[0].Value);
gv_parentInt = intId.ToString();
tbID.Text = gv_parentInt;
strFName = row.Cells[1].Value.ToString();
gv_firstName = strFName.Trim();
tbFName.Text = gv_firstName;
strLName = row.Cells[2].Value.ToString();
gv_lastName = strLName.Trim();
tbLName.Text = gv_lastName;
}
tbMessage.Text = "No Data Here";
}
private void readFriendsData()
{
using (SQLiteConnection conn = new SQLiteConnection($"Data Source = '{"Contacts.db"}';Version=3;"))
{
conn.Open();
// The $ sign and '{String or Integer}' how to add variable to SQL Select Statement'gv_parentInt
// Must incorparate BOTH for SELECT to work
// =================================================================================
using (SQLiteCommand cmd = new SQLiteCommand($"SELECT * FROM FriendsData", conn))
{
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
gv_parentInt = rdr["FID"].ToString().Trim();
gv_firstName = rdr["fxFirstName"].ToString().Trim();
gv_lastName = rdr["fxLastName"].ToString().Trim();
dgvPerson.Rows.Add(gv_parentInt, gv_firstName, gv_lastName);
}
rdr.Close();
}
}
conn.Close();
}
//frmPrintLabel.LoadLabel();
}
public void StyleDGV()
{
this.Controls.Add(dgvPerson);
// Set Design of the DataGridView
dgvPerson.DefaultCellStyle.Font = new Font("Bold Tahoma", 11);
dgvPerson.ColumnCount = 3;
dgvPerson.Columns[0].Width = 60;
dgvPerson.Columns[1].Width = 138;
dgvPerson.Columns[2].Width = 138;
// To Set Col Header Size Mode = Enabled
// To Set Col Header Default Cell Styles DO in Properties
dgvPerson.DefaultCellStyle.BackColor = Color.LightBlue;
dgvPerson.AlternatingRowsDefaultCellStyle.BackColor = Color.LightGray;
dgvPerson.ColumnHeadersHeight = 34;
// DGV Header Names
dgvPerson.Columns[0].Name = " ID";
dgvPerson.Columns[1].Name = "First Name";
dgvPerson.Columns[2].Name = "Last Name";
dgvPerson.Columns[0].HeaderCell.Style.Font = new Font("Bold Tahoma", 11);
dgvPerson.Columns[1].HeaderCell.Style.Font = new Font("Bold Tahoma", 11);
dgvPerson.Columns[2].HeaderCell.Style.Font = new Font("Bold Tahoma", 11);
dgvPerson.Columns[0].HeaderCell.Style.ForeColor = Color.Blue;
dgvPerson.Columns[1].HeaderCell.Style.ForeColor = Color.Blue;
dgvPerson.Columns[2].HeaderCell.Style.ForeColor = Color.Blue;
dgvPerson.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable;
dgvPerson.Columns[1].SortMode = DataGridViewColumnSortMode.NotSortable;
dgvPerson.Columns[2].SortMode = DataGridViewColumnSortMode.NotSortable;
}
private void btnReturn_Click(object sender, EventArgs e)
{
Close();
frmStart fST = new frmStart();
fST.Show();
}
}
}
First let me say that using the TOOL from a VB.Net project was a BIG 4 hour mistake
Here is the code I used to capture the values in the DataGridView
private void dgvPerson_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
int ID = 0;// Declare this top level
ID = Convert.ToInt32(dgvPerson.Rows[e.RowIndex].Cells[0].Value.ToString());
tbID.Text = ID.ToString();
tbFName.Text = dgvPerson.Rows[e.RowIndex].Cells[1].Value.ToString();
tbLName.Text = dgvPerson.Rows[e.RowIndex].Cells[2].Value.ToString();
}
Here is what was WRONG Visual Studio 2019 has two DataGridView Tools
One under All Windows Forms and one under Data (see attached screen shot)
I used the one under All Windows Form in the ToolBox hence my code FAILED
Use the DGV under Data in the ToolBox if your are working with C# and SQLite
I want to update The value of a specific Column for the selected Row in UWP fGrid
Which EventArgs should I use?
public void deleteUser()
{
var recordIndex = this._dtGrid.ResolveToRecordIndex(e.RowColumnIndex.RowIndex);
var mappingName = this._dtGrid.Columns[0].MappingName;
StringBuilder sb = new StringBuilder();
sb.AppendLine(" UPDATE TO USER_INFO SET USE_YN='N' WHERE USER_ID='"+mappingName+"'");
AppInstance.Ins.dbHelper.ExecuteTransaction(sb.ToString());
_isDtChanged = true;
}
Delete button (Appbar)
private void DeleteButton_Click(object sender, RoutedEventArgs e)
{
switch (_headerId)
{
case "userinform":
{
UserinfoModel model = (DataGridFrame.Content as Userinfo.userinfo01).DataContext as UserinfoModel;
model.deleteRow(sender, e);
}
break;
}
}
I solved this problem using 'SelectedItem'!
public void DeleteRow()
{
string del_id = (_dtGrid.SelectedItem as FunctionDataGridModel).id;
StringBuilder sb = new StringBuilder();
sb.AppendLine("UPDATE USER_INFO SET USE_YN ='N' WHERE USER_ID='"+del_id+"'");
AppInstance.Ins.dbHelper.ExecuteScalar(sb.ToString());
}
I have two combobox (combobox1 in form 1 and combobox2 in form2).
I need to import an excel file and the combobox1 gets the sheets name.
Then in the form2 (I don't want to import the same file another time) i have combobox2 that have also the same sheets name from the combobox1.
I tried this but i got the error of NULLFUNCTION Expression(Additional Information: The object reference is not set to an instance of an object).
using (OpenFileDialog openFileDialog = new OpenFileDialog() { Filter = "Excel 97-2003 Workbook|*.xls|Excel Workbook|*.xlsx |fichiers Textes (*.txt)|*.txt|fichiers CSV (*.csv)|*.csv|tous les fichiers (*.*)|*.*" })
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
TextBox_Emplacement.Text = openFileDialog.FileName;
using (var stream = File.Open(openFileDialog.FileName, FileMode.Open, FileAccess.Read))
{
using (IExcelDataReader reader = ExcelReaderFactory.CreateReader(stream))
{
DataSet result = reader.AsDataSet(new ExcelDataSetConfiguration()
{
ConfigureDataTable = (_) => new ExcelDataTableConfiguration() { UseHeaderRow = true }
});
dataTableCollection = result.Tables;
dataTableCollection1 = result.Tables;
sheet.Items.Clear();
//cp.radDropDownList1.Items.Clear();
foreach (DataTable table in dataTableCollection)
sheet.Items.Add(table.TableName);//add sheet to combobox
**Form_Copie cp1 = (Form_Copie)Application.OpenForms["Form_Copie"];
foreach (DataTable table in dataTableCollection)
cp1.radDropDownList1.Items.Add(table.TableName);//add sheet to combobox**
If the item you're trying to pass is just the combobox string value
Could pass the value as you load the new form
{
string sheet = comboBox1.Text;
Form frm2 = new Form2(sheet);
frm2.show();
}
Public Form2(string sheet)
{
Initialize();
comboBox2.Text = sheet;
}
There are a few ways this can be done. Overloading the constructor is a good way, but doing this per control can quickly become daunting and messy. If you want to do this for multiple controls I'd suggest using a model that contains properties of Bindings (eg System.ComponentModel.BindingList and/or System.Forms.Binding) as a field in each form. Then overload the constructor and pass in the bindings through the model class.
public class BindingModel {
public property BindingList<string> ComboBoxBinding {get;set;}
... other binding/non-binding properties ...
}
public class Form1{
private BindingModel _bindingModel = new _bindingModel();
private void Form1_Shown(object sender, EventArgs e) {
this.ComboBox1.DataSource = _bindingModel.ComboBoxBinding;
this.ComboBox1.DataMember = "";
// the add would go in your excel method
_bindingModel.ComboBoxBinding.Add("Item 1");
}
private void btnOpenForm2_Click(object sender, EventArgs e) {
var frm = new Form2(_bindingModel);
frm.Show();
this.Close();
}
}
public class Form2{
private BindingModel _bindingModel = new _bindingModel();
public void Form2(BindingModel bindingModel){
this._bindingModel = bindingModel;
}
// Once the form is shown bind the ComboBox and it will populate the values
private void Form2_Shown(object sender, EventArgs e){
this.ComboBox1.DataSource = _bindingModel.ComboBoxBinding;
this.ComboBox1.DataMember = "";
}
}
Alternatively it is possible to set the controls items within the calling form:
public class Form1{
private void btnOpenForm2_Click(object sender, EventArgs e) {
var frm = new Form2();
for(int i = 0; i < this.ComboBox1.Count - 1; i++){
frm.ComboBox1.Items.Add(ComboBox1.Items[i]);
}
frm.Show();
this.Close();
}
}
I have a form that adds rows into a datatable. So i create the datatable:
DataTable vendas = new DataTable();
Then on Page_Load it creates the Columns:
vendas.Columns.Add("Nome");
vendas.Columns.Add("Morada");
vendas.Columns.Add("Contribuinte");
vendas.Columns.Add("CC");
vendas.Columns.Add("Email");
vendas.Columns.Add("Agregado");
vendas.Columns.Add("Banco");
vendas.Columns.Add("IBAN");
vendas.Columns.Add("Produtos");
And then inside the submit form (button action) it adds the form values as a new row and binds them to a Gridview:
protected void x(object sender, EventArgs e)
{
DataRow venda = vendas.NewRow();
venda["Nome"] = nomecliente;
venda["Morada"] = moradacliente;
venda["Contribuinte"] = contribuintecliente;
venda["CC"] = cccliente;
venda["Email"] = mailcliente;
venda["Agregado"] = agregadocliente;
venda["Banco"] = bancocliente;
venda["IBAN"] = ibancliente;
venda["Produtos"] = produtocliente;
vendas.Rows.Add(venda);
GridviewVendas.DataSource = vendas;
GridviewVendas.DataBind();
}
What is happening tho is that each time it runs this last method it overwrites the previous row instead of adding a new one. I'm doing something wrong and it's probably a dumb mistake but i'm just not seeing it.
EDIT: Here is all that in one:
public partial class _Default : System.Web.UI.Page
{
public string nome;
public string planosaudeantigo;
public string valorplanosaudeantigo;
public string condicoesplanosaudeantigo;
public string stringagregadofamiliar;
public string nomecliente;
public string moradacliente;
public string contribuintecliente;
public string cccliente;
public string mailcliente;
public string agregadocliente;
public string bancocliente;
public string ibancliente;
public string produtocliente;
DataTable vendas = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
vendas.Columns.Add("Nome");
vendas.Columns.Add("Morada");
vendas.Columns.Add("Contribuinte");
vendas.Columns.Add("CC");
vendas.Columns.Add("Email");
vendas.Columns.Add("Agregado");
vendas.Columns.Add("Banco");
vendas.Columns.Add("IBAN");
vendas.Columns.Add("Produtos");
}
protected void InserirVenda_Click(object sender, EventArgs e)
{
nomecliente = NomeCliente.Text;
moradacliente = MoradaCliente.Text;
contribuintecliente = ContribuinteCliente.Text;
cccliente = CCCliente.Text;
mailcliente = MailCliente.Text;
agregadocliente = AgregadoCliente.Text;
bancocliente = BancoCliente.Text;
ibancliente = IbanCliente.Text;
for (int i = 0; i < ProdutosCliente.Items.Count; i++)
{
if (ProdutosCliente.Items[i].Selected)
{
produtocliente += ProdutosCliente.Items[i].Value + ",";
}
}
DataRow venda = vendas.NewRow();
venda["Nome"] = nomecliente;
venda["Morada"] = moradacliente;
venda["Contribuinte"] = contribuintecliente;
venda["CC"] = cccliente;
venda["Email"] = mailcliente;
venda["Agregado"] = agregadocliente;
venda["Banco"] = bancocliente;
venda["IBAN"] = ibancliente;
venda["Produtos"] = produtocliente;
vendas.Rows.Add(venda);
GridviewVendas.DataSource = vendas;
GridviewVendas.DataBind();
}
}
You do it like this:
protected void Page_Load(object sender, EventArgs e)
{
//check if it is a postback
if (!Page.IsPostBack)
{
//create a new table
DataTable vendas = new DataTable();
//add some columns
vendas.Columns.Add("Nome");
vendas.Columns.Add("Morada");
//add the datatable to the viewstate
ViewState["vendas"] = vendas;
}
else
{
//check if the viewstate exits and cast it back to a datatable
if (ViewState["vendas"] != null)
{
vendas = ViewState["vendas"] as DataTable;
}
}
}
And now you can keep adding rows in InserirVenda_Click
Variables are not persisted between postbacks, your DataTable gets reinitialised every time the Page_Load.
You can use Session variables or cookies to persist your data.
How can i get the value of outlet ID it on a comboBox?
here is my code to getting the values from Database and store it on a combobox.
public partial class Addstock : Form
{
String connectionString = ConfigurationManager.ConnectionStrings["TCConnectionString"].ConnectionString;
List<BOStockTransfer> StockList = new List<BOStockTransfer>();
int updateIndex = -1;
public Addstock()
{
InitializeComponent();
}
private void Addstock_Load(object sender, EventArgs e)
{
loadstock();
GetOutlets();
Getproduct();
GetGetWH();
cmdoutletID.Visible = false;
lbloutid.Visible = false;
cmdwh.Visible = false;
lblwh.Visible = false;
}
private void GetOutlets()
{
BOStockTransfer obj_StockTransfer = new BOStockTransfer();
DataSet ds_OutletList = obj_StockTransfer.GetOutlets(connectionString);
if (ds_OutletList.Tables[0].Rows.Count != 0)
{
cmdoutletID.DataSource = ds_OutletList.Tables[0];
cmdoutletID.DisplayMember = "outletId";
}
}
Thank you for your help!
you are setting :
cmdoutletID.Visible = false;
what makes the combobox invisible
you have to set it as follows :
cmdoutletID.Visible = true;
After you added the images , the column name is outletID and Not outletId
so change your code as follows :
private void GetOutlets()
{
BOStockTransfer obj_StockTransfer = new BOStockTransfer();
DataSet ds_OutletList = obj_StockTransfer.GetOutlets(connectionString);
if (ds_OutletList.Tables[0].Rows.Count != 0)
{
cmdoutletID.DataSource = ds_OutletList.Tables[0];
cmdoutletID.DisplayMember = "outletID";
cmdoutletID.ValueMember = "outletID";
cmdoutletID.Enabled = true;
}
}
The combo box has two properties which determine where it loads data from:
DisplayMember
ValueMember
The "ValueMember" property defines which named field populates the ListItem's "ValueProperty". That way, when you do combobox.SelectedItem.Value, you will get the value stored in the named field you specified for "ValueProperty".
Assuming that you are certain that your query is returning rows, perhaps try adding the items "manually" rather than relying on automatic databinding.
private void GetOutlets()
{
BOStockTransfer obj_StockTransfer = new BOStockTransfer();
DataSet ds_OutletList = obj_StockTransfer.GetOutlets(connectionString);
cmdoutletID.DisplayMember = "outletId";
cmdoutletID.ValueMember = "pkID";
cmdoutletID.BeginUpdate();
try
{
cmdoutletID.Items.Clear();
foreach (var row in ds_OutletList.Tables[0].Rows)
cmdoutletID.Items(new { outletid = row["outletid"], pkID = row["primaryKeyIDFieldName"] });
}
finally { cmdoutletID.EndUpdate(); }
}
Try this:
BOStockTransfer obj_StockTransfer = new BOStockTransfer();
DataSet ds_OutletList = obj_StockTransfer.GetOutlets(connectionString);
if (ds_OutletList.Tables[0].Rows.Count != 0)
{
cmdoutletID.DataSource = ds_OutletList.Tables[0];
cmdoutletID.DisplayMember = "outletname";
cmdoutletID.ValueMember = "outletId";
}
To capture selected value, for example on button click:
protected button1_Click(object o, EventArgs e)
{
var selectedId = cmboutletID.SelectedValue;
MessageBox.Show(selectedId);
}