So I'm accessing a DB through a stored procedure and am able to pull the data I wanted into a popup box. The problem now is that no matter what row I click on, the SAME data keeps populating my fields. How the heck can I choose a particular row, and have that specific row's data pulled from the DB? Thanks for any help
Form1
public partial class DSC_Mon : Form
{
DSCU_SvcConsumer.MTCaller Caller;
DataSet dsZA;
DataSet dsOut;
public DSC_Mon()
{
InitializeComponent();
Caller = new DSCU_SvcConsumer.MTCaller();
dsZA = new DataSet();
dsOut = new DataSet();
}
private void DSC_Mon_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void LoadData()
{
if (!dsZA.Tables.Contains("Query"))
{
DataTable dtZA = dsZA.Tables.Add("Query");
dtZA.Columns.Add("str");
dtZA.Rows.Add(string.Format(#"exec MON_GetStatus"));
}
//dtZA.Rows.Add(string.Format(#"select * from am_company"));
dsOut.Clear();
dsOut.Merge(Caller.CallRequest("ZuluAction", dsZA));
if (gridEXMon.DataSource == null)
{
gridEXMon.DataSource = dsOut;
gridEXMon.DataMember = "Table";
}
//gridEXMon.RetrieveStructure();
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Enabled = false;
LoadData();
timer1.Enabled = true;
}
private void gridEXMon_DoubleClick(object sender, EventArgs e)
{
ReportInfo report = new ReportInfo();
report.ShowDialog();
}
}
I replaced the private void gridEXMon_DoubleClick with:
private void gridEXMon_RowDoubleClick(object sender, Janus.Windows.GridEX.RowActionEventArgs e)
{
if (e.Row.RowIndex < 0)
return;
int rowIndex = Convert.ToInt32(e.Row.RowIndex);
ReportInfo report = new ReportInfo(rowIndex);
report.ShowDialog();
}
Popup Dialog
public partial class ReportInfo : Form
{
public ReportInfo()
{
InitializeComponent();
DSCU_SvcConsumer.MTCaller caller = new DSCU_SvcConsumer.MTCaller();
DataSet dsZA = new DataSet();
DataSet dsOut = new DataSet();
if (!dsZA.Tables.Contains("Query"))
{
DataTable dtZA = dsZA.Tables.Add("Query");
dtZA.Columns.Add("str");
dtZA.Rows.Add(string.Format(#"MON_ReportInfo"));
}
dsOut.Clear();
dsOut.Merge(caller.CallRequest("ZuluAction", dsZA));
DataTable dt = dsOut.Tables["Table"];
DataRow dr = dt.Rows[0];
if (dt != null)
{
systemNameTextBox.Text = dr["System"].ToString();
contactName1TextBox.Text = dr["Manager"].ToString();
functionNameTextBox.Text = dr["Function"].ToString();
durationMSTextBox.Text = dr["Speed"].ToString();
}
}
I then sent the rowIndex to the popup:
DataTable dt = dsOut.Tables["Table"];
DataRow dr = dt.Rows[rowIndex];
systemNameTextBox.Text = dr["System"].ToString();
contactName1TextBox.Text = dr["Manager"].ToString();
functionNameTextBox.Text = dr["Function"].ToString();
durationMSTextBox.Text = dr["Speed"].ToString();
}
Better to get the data from the grid to save the extra call to the database in your ReportInfo class.
Here is the code:
private void gridEXMon_DoubleClick(object sender, EventArgs e)
{
if (e.Row.RowIndex < 0)
return;
ReportInfo report = new ReportInfo();
String System = Convert.ToInt32(e.Row.Cells["System"].Value);
String Manager = Convert.ToString(e.Row.Cells["Manager"].Value);
String Function = Convert.ToDecimal(e.Row.Cells["Function"].Value);
String Speed = Convert.ToInt32(e.Row.Cells["Speed"].Value);
report.ShowDialog(System, Manager, Function, Speed);
}
Then your ReportInfo class ctor should be:
public partial class ReportInfo : Form
{
public ReportInfo(String System, String Manager, String Function, String Speed)
{
InitializeComponent();
systemNameTextBox.Text = System;
contactName1TextBox.Text = Manager;
functionNameTextBox.Text = Function;
durationMSTextBox.Text = Speed;
}
}
Have you tried with:
gridEXMon.DataSource = dsOut.Tables[0];
// next line is not required if you've already defined proper grid structure
gridEXMon.RetrieveStructure();
Janus has also his own forum available here. You can find there a lot of useful information. For browsing I will use IE. Janus forum works good only with IE...
Edited:
How ReportInfo class can know what record have you selected? Especially that you have fallowing code:
DataTable dt = dsOut.Tables["Table"];
DataRow dr = dt.Rows[0]; // always first record is taken!
Probably you should define ctor with row index:
public ReportInfo(int rowIndex)
{
...
DataTable dt = dsOut.Tables["Table"];
DataRow dr = dt.Rows[rowIndex];
....
}
Related
On a windows form I have two unbound data grid view columns each with their own header and I am trying read a csv file in a datatable and bind it to the grid.
Only I don't know the logic involved. I don't know how to bind the data to the 2 data grid view columns. There is a lot of samples out there of how to bind csv data to a grid view but they deal with headers that get read from inside a file and not unbound ones except for this but that's with asp. Display data on grid view column programmatically
Here is the data from the csv file.
Address,76 Douglas St Wakecorn
Property name,Wakecorn University
Building,C Block
Room,C2.18
Here is the code for the class that reads it.
public class Setting
{
private DataTable _dt { get; set; }
public DataTable ProcessSettingFileCMD(string filePath)
{
if (_dt == null)
{
populateControlWithCSVData(filePath);
}
}
private void populateControlWithCSVData(string filePath)
{
_dt = new DataTable();
string[] lines = File.ReadAllLines(filePath);
if(lines.Length > 0)
{
for(int row = 1; row < lines.Length; row++)
{
string[] dataWords = lines[row].Split(',');
DataRow dr = _dt.NewRow();
foreach (string word in lines)
{
dr[word] = dataWords[row++];
}
_dt.Rows.Add(dr);
}
}
}
}
Here is the form
private void mnuOpen_Click(object sender, EventArgs e)
{
openFD.InitialDirectory = "C:\\";
openFD.ShowDialog();
_dt = _objSetting.ProcessSettingFileCMD(openFD.FileName);
if (_dt.Rows.Count > 0)
{
gvSettings.DataSource = _dt;
}
}
The error being returned is here on dr[word] = dataWords[row++];
System.ArgumentException: 'Column 'Address,76 Douglas St Wakecorn'
does not belong to table .
As per the guidance and options provided I have taken out the columns made in the designer and instead instanced them when reading a CSV file.
Also I have used a CsvFileReader child class to bind it to a string list and then to a data table. Highly useful! http://www.blackbeltcoder.com/Articles/files/reading-and-writing-csv-files-in-c
Here is the rewritten code.
Settings Form.
public partial class frmSettings : Form
{
protected string FileName;
protected bool Modified;
Setting _objSetting = new Setting();
OpenFileDialog openFD = new OpenFileDialog();
DataTable _dt = new DataTable();
public frmSettings()
{
InitializeComponent();
}
private void mnuOpen_Click(object sender, EventArgs e)
{
Cursor = Cursors.WaitCursor;
try
{
openFD.Title = "Open a CSV File";
if (SaveIfModified())
{
if (openFD.ShowDialog(this) == DialogResult.OK)
{
_dt = _objSetting.ProcessSettingFileCMD(openFD.FileName);
if (_dt.Rows.Count > 0)
{
gvSettings.DataSource = _dt;
}
}
}
FileName = openFD.FileName;
Modified = false;
}
catch (Exception ex)
{
Debug.WriteLine(String.Format("Error reading from {0}.\r\n\r\n{1}", FileName, ex.Message));
}
finally
{
Cursor = Cursors.Default;
}
}
}
Here is the Settings class again.
public class Setting
{
private DataTable _dt;
DataColumn _dclColumnDescription = new DataColumn("Description", typeof(string));
DataColumn _dclColumnData = new DataColumn("Data", typeof(string));
public DataTable ProcessSettingFileCMD(string filePath)
{
if (_dt == null)
{
populateControlWithCSVData(filePath);
}
}
private void populateControlWithCSVData(string filePath)
{
_dt = new DataTable();
List<string> columns = new List<string>();
using (var reader = new CsvFileReader(filePath))
{
_dt.Columns.Add(_dclColumnDescription);
_dt.Columns.Add(_dclColumnData);
while (reader.ReadRow(columns))
{
_dt.Rows.Add(columns.ToArray());
}
}
}
}
I always wanted my code to be cleaner and readable. I'm here in order to achieve that. Since i'm a beginner, it's better to learn this early. Like calling all of them in a class, I don't want too see these many codes in my form. I hope someone would be able to give me a suggestions and a proper way of doing these.
Here's my code
public partial class SIMSSupplier : UserControl
{
ADDSupplier supply;
ADDPReturns returns;
public SIMSSupplier()
{
InitializeComponent();
}
public DataTable dbdataset;
public DataSet ds = new DataSet();
public string ID = "SPPLR-000";
public int DeliveryID, OrderID, ReturnID;
DataView db;
DataTable dt = new DataTable();
private void Supplierview_SelectionChanged(object sender, EventArgs e)
{
var row = Supplierview.CurrentCell.RowIndex;
SupplierID.Text = Supplierview.Rows[row].Cells[0].Value.ToString();
CompanyName.Text = Supplierview.Rows[row].Cells[1].Value.ToString();
ContactName.Text = Supplierview.Rows[row].Cells[2].Value.ToString();
ContactNumber.Text = Supplierview.Rows[row].Cells[3].Value.ToString();
Date.Text = Supplierview.Rows[row].Cells[4].Value.ToString();
Address.Text = Supplierview.Rows[row].Cells[5].Value.ToString();
Remarks.Text = Supplierview.Rows[row].Cells[6].Value.ToString();
}
private void PurchaseOrder_SelectionChanged(object sender, EventArgs e)
{
var row = PurchaseOrder.CurrentCell.RowIndex;
txt_purchase.Text = PurchaseDeliveries.Rows[row].Cells[0].Value.ToString();
txt_supplier.Text = PurchaseDeliveries.Rows[row].Cells[1].Value.ToString();
txt_item.Text = PurchaseDeliveries.Rows[row].Cells[2].Value.ToString();
txt_date.Text = PurchaseDeliveries.Rows[row].Cells[3].Value.ToString();
txt_quantity.Text = PurchaseDeliveries.Rows[row].Cells[4].Value.ToString();
txt_cost.Text = PurchaseDeliveries.Rows[row].Cells[5].Value.ToString();
txt_amount.Text = PurchaseDeliveries.Rows[row].Cells[6].Value.ToString();
txt_sales.Text = PurchaseDeliveries.Rows[row].Cells[7].Value.ToString();
txt_code.Text = PurchaseDeliveries.Rows[row].Cells[8].Value.ToString();
txt_patient.Text = PurchaseDeliveries.Rows[row].Cells[9].Value.ToString();
}
private void PurchaseDeliveries_SelectionChanged(object sender, EventArgs e)
{
var row = PurchaseDeliveries.CurrentCell.RowIndex;
PurchaseID.Text = PurchaseDeliveries.Rows[row].Cells[0].Value.ToString();
Supplier.Text = PurchaseDeliveries.Rows[row].Cells[1].Value.ToString();
ItemDescription.Text = PurchaseDeliveries.Rows[row].Cells[2].Value.ToString();
Dates.Text = PurchaseDeliveries.Rows[row].Cells[3].Value.ToString();
Quantity.Text = PurchaseDeliveries.Rows[row].Cells[4].Value.ToString();
Unitcost.Text = PurchaseDeliveries.Rows[row].Cells[5].Value.ToString();
Amount.Text = PurchaseDeliveries.Rows[row].Cells[6].Value.ToString();
SalesInvoice.Text = PurchaseDeliveries.Rows[row].Cells[7].Value.ToString();
Codeitems.Text = PurchaseDeliveries.Rows[row].Cells[8].Value.ToString();
Patientname.Text = PurchaseDeliveries.Rows[row].Cells[9].Value.ToString();
}
private void PurchaseReturn_SelectionChanged(object sender, EventArgs e)
{
var row = PurchaseReturn.CurrentCell.RowIndex;
txt_return.Text = PurchaseReturn.Rows[row].Cells[0].Value.ToString();
txt_rsupplier.Text = PurchaseReturn.Rows[row].Cells[1].Value.ToString();
txt_ritem.Text = PurchaseReturn.Rows[row].Cells[2].Value.ToString();
txt_rmodel.Text = PurchaseReturn.Rows[row].Cells[3].Value.ToString();
txt_rsrp.Text = PurchaseReturn.Rows[row].Cells[4].Value.ToString();
txt_rcode.Text = PurchaseReturn.Rows[row].Cells[5].Value.ToString();
txt_rdate.Text = PurchaseReturn.Rows[row].Cells[6].Value.ToString();
txt_rremarks.Text = PurchaseReturn.Rows[row].Cells[7].Value.ToString();
}
}
the first can simplify as the following:
private void Supplierview_SelectionChanged(object sender, EventArgs e)
{
var row = Supplierview.CurrentRow;
SupplierID.Text = row.Cells[0].Value.ToString();
CompanyName.Text = row.Cells[1].Value.ToString();
ContactName.Text = row.Cells[2].Value.ToString();
ContactNumber.Text = row.Cells[3].Value.ToString();
Date.Text = row.Cells[4].Value.ToString();
Address.Text = row.Cells[5].Value.ToString();
Remarks.Text = row.Cells[6].Value.ToString();
}
the second , i would recommend use objects collection as a datasource for your grid. For example :
class DataItem{
public string SupplierID {get;set;}
public string CompanyName {get;set;}
.....
}
Supplierview.DataSource = "collection of DataItem"
then
private void Supplierview_SelectionChanged(object sender, EventArgs e)
{
var dataItem = dataGridView1.CurrentRow.DataBoundItem as DataItem;
if (dataItem != null)
{
SupplierID.Text = dataItem.SupplierID;
.....
}
}
I suggest using DataBinding for this, then there is no code needed to perform the actions in your sample.
If you dont want to use databinding you could simply make use of private methods to organize your code.
For example
#region Supplier Stuff
private void SupplierViewChanged(DataRow row)
{
SupplierID.Text = row.Cells[0].Value.ToString();
CompanyName.Text = row.Cells[1].Value.ToString();
ContactName.Text = row.Cells[2].Value.ToString();
ContactNumber.Text = row.Cells[3].Value.ToString();
Date.Text = row.Cells[4].Value.ToString();
Address.Text = row.Cells[5].Value.ToString();
Remarks.Text = row.Cells[6].Value.ToString();
}
// put all other helper methods that deal with Supplier here...
#endregion Supplier Stuff
private void Supplierview_SelectionChanged(object sender, EventArgs e)
{
SupplierViewChanged(Supplierview.CurrentRow);
}
This makes your code a bit more organized and readable, but databinding is still the method I would choose
I have a custom control that I created and it was working when everything was single thread. It does update with the first message before I send it off to the interface.
I have a datatable:
DataTable dtNew = new DataTable(szTableName); // to add into a dataset later
dtNew.Columns.Add("EventDate",typeof(string));
dtNew.Columns.Add("Function",typeof(string));
dtNew.Columns.Add("IsError",typeof(bool));
dtNew.Columns.Add("LongMessage",typeof(string));
dtNew.Columns.Add("Message",typeof(string));
dtNew.Columns.Add("Process",typeof(string));
dtNew.Columns.Add("RecID",typeof(string));
dtNew.Columns.Add("Thread",typeof(string));
dtNew.Columns.Add("UserName", typeof(string));
ProcessStatus NewPanel = new ProcessStatus(); // create custom control
NewPanel.SetDataSource(ref dtNew); // sets the datasource to the datatable
dsLogs.Tables.Add(dtNew); // add datatable into dataset
Custom control receives the datasource so it should be bound:
public partial class ProcessStatus : UserControl
{
public ProcessStatus()
{
InitializeComponent();
}
public void SetProcess(string szProcName)
{
lblProcess.Text = "Process: " + szProcName;
}
public void SetThread(string szThreadName)
{
lblThreadNum.Text = "Thread: " + szThreadName;
}
public void SetDataSource(ref DataTable dtTable)
{
dgvProcess.DataSource = dtTable;
dgvProcess.Columns["EventDate"].Visible = false;
//dgvProcess.Columns["Function"].Visible = false;
dgvProcess.Columns["IsError"].Visible = false;
dgvProcess.Columns["LongMessage"].Visible = false;
//dgvProcess.Columns["Message"].Visible = false;
dgvProcess.Columns["Process"].Visible = false;
dgvProcess.Columns["RecID"].Visible = false;
dgvProcess.Columns["Thread"].Visible = false;
dgvProcess.Columns["UserName"].Visible = false;
dgvProcess.Columns["Function"].Width = 80;
dgvProcess.Columns["Message"].Width = 200;
}
// only show first line
private void dgvProcess_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
if (dgvProcess.RowCount > 0)
dgvProcess.FirstDisplayedScrollingRowIndex = dgvProcess.RowCount - 1;
}
}
When the datatable is updated with a new message, that message is not updated in the custom control (in the datagrid). Again, this did work on single thread so I'm probably not doing something right to allow this to update crossthreads or something like that...
I have create a win forms with a datagridview. Where i can insert update delete
articles from the database.
But i need a wpf not a win forms project. The problem is in wpf you don't have a datagridview.
Now i have try for let work it with a datagrid but there are no row options.
i have already found how i can load the data from the wcf in my datagrid with this DgArtikel.ItemsSource = ds.Tables[0].DefaultView;
but how can i let work the insert update and delete button ?
public partial class Form1 : Form
{
ServiceReference1.Service1Client objService = new ServiceReference1.Service1Client(); // Add service reference
public Form1()
{
InitializeComponent();
showdata();
}
private void showdata() // To show the data in the DataGridView
{
DataSet ds,ds2 = new DataSet();
ds = objService.SelectUserDetails();
ds2 = objService.SelectCombobox();
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
ComboBoxCategorie.DataSource = ds2.Tables[0];
ComboBoxCategorie.DisplayMember = "Categorie";
}
private void btnClear_Click(object sender, EventArgs e)
{
int i = dataGridView1.SelectedCells[0].RowIndex;
textBoxArtikel.Text = dataGridView1.Rows[i].Cells[1].Value.ToString();
textBoxOmschrijving.Text = dataGridView1.Rows[i].Cells[2].Value.ToString();
textBoxVerkoopprijs.Text = dataGridView1.Rows[i].Cells[3].Value.ToString();
textBoxInStock.Text = dataGridView1.Rows[i].Cells[4].Value.ToString();
ComboBoxCategorie.SelectedValue = dataGridView1.Rows[i].Cells[5].Value.ToString();
}
private void btnSave_Click(object sender, EventArgs e)
{
ServiceReference1.UserDetails objuserdetail = new ServiceReference1.UserDetails(); // Add type reference
// objuserdetail.UserID = count;
objuserdetail.Artikel = textBoxArtikel.Text;
objuserdetail.Omschrijving = textBoxOmschrijving.Text;
objuserdetail.Verkoopprijs = Convert.ToInt32(textBoxVerkoopprijs.Text);
objuserdetail.Instock = Convert.ToInt32(textBoxInStock.Text);
objuserdetail.Cat_id = ComboBoxCategorie.SelectedIndex;
objService.InsertUserDetails(objuserdetail); // To insert the data
showdata();
}
private void btnDelete_Click(object sender, EventArgs e)
{
ServiceReference1.UserDetails objuserdetail = new ServiceReference1.UserDetails();
if (dataGridView1.Rows.Count > 1)
{
DataTable dt = new DataTable();
// objuserdetail.UserID = (int)dataGridView1.CurrentRow.Cells[0].Value;
objService.DeleteUserDetails(objuserdetail); // To Delete the data
showdata();
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
ServiceReference1.UserDetails objuserdetail = new ServiceReference1.UserDetails();
objuserdetail.Artikel_id = (int)dataGridView1.CurrentRow.Cells[0].Value;
objuserdetail.Artikel = textBoxArtikel.Text;
objuserdetail.Omschrijving = textBoxOmschrijving.Text;
objuserdetail.Verkoopprijs = Convert.ToInt32(textBoxVerkoopprijs.Text);
objuserdetail.Instock = Convert.ToInt32(textBoxInStock.Text);
objService.UpdateRegistrationTable(objuserdetail); // To Update the Data
showdata();
textBoxArtikel.Text = "";
textBoxOmschrijving.Text = "";
textBoxVerkoopprijs.Text = "";
textBoxInStock.Text = "";
}
}
}
How can i get multiple selected rows in gridview using c# code & that selected rows i have to display in another form which also have gridview
public partial class WindowForm: Form
{
private DataTable dataTable = new DataTable();
//This will contain all the selected rows.
private List<DataGridViewRow> selectedRows = new List<DataGridViewRow>();
public WindowForm()
{
InitializeComponent();
dataTable .Columns.Add("Column1");
dataTable .Columns.Add("Column2");
dataTable .Columns.Add("Column3");
for (int i = 0; i < 30; i++)
{
dataTable .Rows.Add(i, "Row" + i.ToString(), "Item" + i.ToString());
}
dataGridView1.DataSource = dataTable ;
//This will select full row of a grid
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
//This will allow multi selection
dataGridView1.MultiSelect = true;
dataGridView1.CurrentCellChanged += new EventHandler(dataGridView1_CurrentCellChanged);
dataGridView1.CellBeginEdit += new DataGridViewCellCancelEventHandler(dataGridView1_CellBeginEdit);
}
void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
PerformSelection(dataGridView1, selectedRows);
}
void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
{
if (selectedRows.Contains(dataGridView1.CurrentRow))
{
selectedRows.Remove(dataGridView1.CurrentRow);
}
else
{
selectedRows.Add(dataGridView1.CurrentRow);
}
PerformSelection(this.dataGridView1, selectedRows);
}
private void PerformSelection(DataGridView dgv, List<DataGridViewRow> selectedRowsCollection)
{
foreach (DataGridViewRow dgvRow in dgv.Rows)
{
if (selectedRowsCollection.Contains(dgvRow))
{
dgvRow.Selected = true;
}
else
{
dgvRow.Selected = false;
}
}
}
}