Retrieve data datagrid to form - c#

I have created a form to insert data. When data inserted it shows into datagridview1. I use dataGridView1_MouseClick event to retrieve data into the form. I successfully retrieved textbox data only into my form. I want to retrieve checkbox value which is checked or not. How can i retrieve checkbox value by clicking dataGridView1_MouseClick event.
I use following code for that:
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
try
{
txtID.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
Name.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
}
catch (ApplicationException ex)
{
MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
}
My result is here
But I want like this:

U can retrive values of other fields in similar like u did
This is for WPF control Checkbox link
I assume checkbox name of movie is movie_chbox
movie_chbox.IsChecked =
dataGridView1.SelectedRows[0].Cells[3].Value.toString() == "1" ?true:false
Similarly you can do same for other too.
This is for winforms control Checkbox link
movie_chbox.Checked =
dataGridView1.SelectedRows[0].Cells[3].Value.toString() == "1" ?true:false

Instead of displaying 0 or 1 in datagridview display "Interested"/"Not Interested" and when you insert/update to database that time insert/update as 0 or 1 for better database mentainance.

Use the checked property of the check box control in your code and change the code for different categories. In your case the final code will be be something like below:
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
try
{
txtID.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
txtName.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
string isCheckedMovie = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
string isCheckedSports = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
string isCheckedReading = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
string isCheckedWriting = dataGridView1.SelectedRows[0].Cells[5].Value.ToString();
if (isCheckedMovie == "1")
movieBox.Checked = true;
else
movieBox.Checked = false;
if (isCheckedSports == "1")
sportsBox.Checked = true;
else
sportsBox.Checked = false;
if (isCheckedReading == "1")
readingBox.Checked = true;
else
readingBox.Checked = false;
if (isCheckedWriting == "1")
writingBox.Checked = true;
else
writingBox.Checked = false;
}
catch (ApplicationException ex)
{
MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}

Related

retain previous value of text box till the form is closed

I am very new to c# , and learning to make data entry application,
in my entry form when the user clicks save all the data text boxes are refreshed and saved to database and the text box appears empty to enter gain. This is a continuous process.
Now i want my textbox1 to retain the same value where the user first entered till the form is closed.
Please help me how to achieve this?
i tried this code but the textbox is still empty:
private string value;
private void materiaNumberTextBox_TextChanged(object sender, EventArgs e)
{
var oldValue = value;
value = ((TextBox)sender).Text; // text1.Text
}
here's the code that does while saving:
private void btnsave_Click(object sender, EventArgs e)
{
try
{
String msg = "Confirm Save?";
String caption = "Save Record";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
MessageBoxIcon ico = MessageBoxIcon.Question;
DialogResult result;
result = MessageBox.Show(this, msg, caption, buttons, ico);
if (result == DialogResult.Yes)
{
generateautoID();
this.iP_SpoolsBindingSource.EndEdit();
MessageBox.Show("The Record saved Successfully:" + outputSpoolNoTextBox.Text, "Save_Update",
MessageBoxButtons.OK, MessageBoxIcon.Information);
this.iP_SpoolsTableAdapter.Update(this.pINQCDataSet.IP_Spools);
this.iP_SpoolsTableAdapter.Fill(this.pINQCDataSet.IP_Spools);
//MessageBox.Show("The Record saved Successfully:", "Save_Update",
//MessageBoxButtons.OK, MessageBoxIcon.Information);
this.iP_SpoolsBindingSource.AddNew();
string strStartenddateformat = "dd-MM-yyyy";
materialTypeComboBox.ValueMember = "Tungsten";
unitComboBox.ValueMember = "Mic";
statusComboBox.ValueMember = "Accepted";
cFComboBox.ValueMember = "";
bowOutOfComboBox.ValueMember = "";
ductilityOutofComboBox.ValueMember = "";
finishUOMComboBox.ValueMember = "Mic";
finishTypeComboBox.ValueMember = "Clean";
rejectReason1ComboBox.ValueMember = "";
rejectReason2ComboBox.ValueMember = "";
rejectReason3ComboBox.ValueMember = "";
lotNoTextBox.Text = "0";
dOEDateTimePicker.Format = DateTimePickerFormat.Custom;
dOEDateTimePicker.CustomFormat = strStartenddateformat;
dOEDateTimePicker.Value = DateTime.Now;
dOPDateTimePicker.Format = DateTimePickerFormat.Custom;
dOPDateTimePicker.CustomFormat = strStartenddateformat;
dOPDateTimePicker.Value = DateTime.Now;
}
else
{
return;
}
}
catch (Exception ex)
{
MessageBox.Show("Saving Failed:" + ex.Message.ToString(), "Save",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
here's the image of my form:
You can try the following code to save the first input text in the textbox.
Please use the event textbox_Leave event.
private void button1_Click(object sender, EventArgs e)
{
//Update the database
MessageBox.Show("Update success");
textBox1.Text = textbox; // return to the first input in the textbox
}
int i = 0;
string textbox = "";
private void textBox1_Leave(object sender, EventArgs e)
{
if (i == 0)
{
textbox = textBox1.Text;
i++;
}
}
Result:
Use a data reader to get the values from database and then populate values in textbox using those values.

c# Populating a ListView from an XML File

I am still learning my way around c# and am trying to populate my ListView from an XML file.
Below is a picture of my ListView:
ListView
When I click a button on my UI, it reads the XML file using this code (Configuration.cs) here:
public static void LoadConfiguration(MainUI UIForm)
{
XDocument doc = XDocument.Load("E:\\InnerSpace" + "\\Scripts\\BJScripts\\MySettings.xml");
MainUI uI = new MainUI();
UIForm.addItemsToActionsListView(doc.Element("UABA").Element("Configure_Tab").Element("Actions_List").Element("ListItem_1").Attribute("Position_X").Value, doc.Element("UABA").Element("Configure_Tab").Element("Actions_List").Element("ListItem_1").Attribute("Position_Y").Value, doc.Element("UABA").Element("Configure_Tab").Element("Actions_List").Element("ListItem_1").Attribute("RGB").Value, doc.Element("UABA").Element("Configure_Tab").Element("Actions_List").Element("ListItem_1").Attribute("Is_Colour").Value, doc.Element("UABA").Element("Configure_Tab").Element("Actions_List").Element("ListItem_1").Attribute("Target").Value, doc.Element("UABA").Element("Configure_Tab").Element("Actions_List").Element("ListItem_1").Attribute("Press_Button").Value);
}
Then it calls a method in my MainUI.cs and passes the relevant information I need to it.
public partial class MainUI : Form
{
public MainUI()
{
InitializeComponent();
}
private void MainUI_FormClosing(object sender, FormClosingEventArgs e)
{
Program._bMustShutdown = true;
}
public void NewActionsConsoleMessage(string Input)
{
ActionsConsole.Items.Add(DateTime.Now.ToString("h:mm:ss tt") + ": " + Input);
ActionsConsole.SelectedIndex = (ActionsConsole.Items.Count - 1);
}
private void btnAddAction_Click(object sender, EventArgs e)
{
if (txtboxLocationX.Text.Length == 0)
{
NewActionsConsoleMessage("ERROR: Enter a value for Position X and try again.");
MessageBox.Show("Enter a value for Position X and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (txtboxLocationY.Text.Length == 0)
{
NewActionsConsoleMessage("ERROR: Enter a value for Position Y and try again.");
MessageBox.Show("Enter a value for Position Y and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (txtboxColourRGB.Text.Length == 0)
{
NewActionsConsoleMessage("ERROR: Enter a value for Pixel RGB and try again.");
MessageBox.Show("Enter a value for Pixel RGB and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (!radionbtnIsColour.Checked && !radionbtnIsNotColour.Checked)
{
NewActionsConsoleMessage("ERROR: Select either tracking by colour or tracking my not colour and try again.");
MessageBox.Show("Select either tracking by colour or tracking my not colour and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (cboxTarget.Text.Length == 0)
{
NewActionsConsoleMessage("ERROR: Select a target and try again.");
MessageBox.Show("Select a target and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (txtboxActionBtn.Text.Length == 0)
{
NewActionsConsoleMessage("ERROR: Enter a value for Action to Take Button Press and try again.");
MessageBox.Show("Enter a value for Action to Take Button Press and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
ListViewItem addActionsItem = new ListViewItem(txtboxLocationX.Text);
addActionsItem.SubItems.Add(txtboxLocationY.Text);
addActionsItem.SubItems.Add(txtboxColourRGB.Text);
addActionsItem.SubItems.Add(radionbtnIsColour.Checked.ToString());
addActionsItem.SubItems.Add(cboxTarget.Text);
addActionsItem.SubItems.Add(txtboxActionBtn.Text);
lvActionsList.Items.Add(addActionsItem);
}
private void btnSetPixelLocationColour_Click(object sender, EventArgs e)
{
var pixelColourPickerUI = new PixelColourPickerUI();
pixelColourPickerUI.ShowDialog();
txtboxLocationX.Text = pixelColourPickerUI._SelectedPixelMouseLocX;
txtboxLocationY.Text = pixelColourPickerUI._SelectedPixelMouseLocY;
txtboxColourRGB.Text = pixelColourPickerUI._SelectedPixelColor_R + "," + pixelColourPickerUI._SelectedPixelColor_G + "," + pixelColourPickerUI._SelectedPixelColor_B;
pnlConfigurePixelColour.BackColor = Color.FromArgb(pixelColourPickerUI._SelectedPixelColor_A, pixelColourPickerUI._SelectedPixelColor_R, pixelColourPickerUI._SelectedPixelColor_G, pixelColourPickerUI._SelectedPixelColor_B);
}
public ListView.ListViewItemCollection listViewItemCollection
{
get { return lvActionsList.Items; }
}
public void addItemsToActionsListView(string _LocX, string _LocY, string _RGB, string _IsColour, string _Target, string _ButtonPress)
{
Debug.WriteLine("_LocX: " + _LocX + "_LocY" + _LocY + "_RGB" + _RGB + "_IsColour" + _IsColour + "_Target" + _Target + "_ButtonPress" + _ButtonPress);
ListViewItem addActionsItem = new ListViewItem(_LocX);
addActionsItem.SubItems.Add(_LocY);
addActionsItem.SubItems.Add(_RGB);
addActionsItem.SubItems.Add(_IsColour);
addActionsItem.SubItems.Add(_Target);
addActionsItem.SubItems.Add(_ButtonPress);
Debug.WriteLine("Count: " + addActionsItem.SubItems.Count);
lvActionsList.Items.Add(addActionsItem);
}
private void btnSaveActionsList_Click(object sender, EventArgs e)
{
Configuration.Configuration.SaveConfiguration(items: lvActionsList.Items);
}
private void btnLoadProfile_Click(object sender, EventArgs e)
{
Configuration.Configuration.LoadConfiguration(this);
}
}
The first Debug.WriteLine returns the proper passed variables from Configuration.cs and the second Debug.WriteLine returns the proper count of 6 SubItems.
However, when viewing my ListView, it is still empty. Previously, I was able to add the the ListView using identical code (with different variables) when I was making what eventually became the XML file information. What am I doing wrong when trying to load the information from the XML? Do you need to see more code?
Thanks in advance!
Pass in the MainUI as argument to your static method:
public static void LoadConfiguration(MainUI UiForm)
{
XDocument doc = XDocument.Load("E:\\InnerSpace" + "\\Scripts\\BJScripts\\MySettings.xml");
UiForm.addItemsToActionsListView(doc.Element("UABA" etc
}

How to compare new and previous value in combobox?

i have datagridview and column in it,and type is combobox.Combobox value's are used from sql data base.In combobox "Status" i have 5 different item value's.What i want is that when i change item value from combobox and press "save" button ,i want to check which value was before this one(before save) and say:
private void m02BindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
try
{
if (StatusTextBox.Text == "3" && // + want to ask here if previous statusTextBox.text was "1" then to execute lines down if not goes to 'else')
{
DialogResult mbox = MessageBox.Show("do you want to save today's date and time?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
datumOtvaranjaDateTimePicker.Focus();
if (mbox == DialogResult.Yes)
{
datumOtvaranjaDateTimePicker.Value = DateTime.Now;
}
Save();
Refresh();
}
else
{
MessageBox.Show("you cant do that!!!" + Environment.NewLine + "Check what you typed and try again", "Upozorenje", MessageBoxButtons.OK, MessageBoxIcon.Warning);
Refresh();
}
}
catch (Exception)
{
}
}
Look at this other answer
You can handle the ComboBox.Enter event. Then save off the
SelectedItem or SelectedValue to a member variable
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
comboBox1.Enter += comboBox1_Enter;
}
private void comboBox1_Enter(object sender, EventArgs e)
{
m_cb1PrevVal = comboBox1.SelectedValue;
}
private void RestoreOldValue()
{
comboBox1.SelectedValue = m_cb1PrevVal;
}
}

How to rebind datasource to a winform DataGridView Combobox column?

I have a DataGridView in winform with 2 combo box columns: 1) Companies, 2) Accounts.
I want to update the accounts combo box according to the selected company.
I have this code:
void recipientsDataGrid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
try
{
ComboBox cb = e.Control as ComboBox;
if (cb != null)
{
cb.SelectedValueChanged -= new EventHandler(companyCombobox_SelectedValueChanged);
cb.SelectedValueChanged += new EventHandler(companyCombobox_SelectedValueChanged);
}
}
catch (Exception ex)
{
}
}
private void companyCombobox_SelectedValueChanged(object sender, EventArgs e)
{
try
{
var currentCell = recipientsDataGrid.CurrentCellAddress;
if (currentCell.X == 3)
{
var sendingCB = sender as DataGridViewComboBoxEditingControl;
int companyId = sendingCB.SelectedValue.ToInt();
DataTable dtAccounts = m_CustomersFunctions.GetCompanyAccounts(companyId);
DataGridViewComboBoxCell cboAccounts = (DataGridViewComboBoxCell)recipientsDataGrid.Rows[currentCell.Y].Cells["Account"];
cboAccounts.ValueMember = "account_id";
cboAccounts.DisplayMember = "AccountName";
cboAccounts.DataSource = dtAccounts;
int defaultAccountId = (from row in dtAccounts.AsEnumerable()
where row.Field<string>("AccountName").EndsWith("*")
select row.Field<int>("account_id")).FirstOrDefault();
if (defaultAccountId > 0)
cboAccounts.Value = defaultAccountId;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
It works fine in the first time I select a company, but when I change the company and try to update the data source for the accounts combo box I'm getting an error:
I tried to add the items manualy and not with a DataSource, and I got the same error.
How can I fix it ?
please...
Try to clear the value of accounts cell before rebind it, like this:
private void companyCombobox_SelectedValueChanged(object sender, EventArgs e)
{
try
{
var currentCell = recipientsDataGrid.CurrentCellAddress;
if (currentCell.X == 3)
{
var sendingCB = sender as DataGridViewComboBoxEditingControl;
int companyId = sendingCB.SelectedValue.ToInt();
DataTable dtAccounts = m_CustomersFunctions.GetCompanyAccounts(companyId);
DataGridViewComboBoxCell cboAccounts = (DataGridViewComboBoxCell)recipientsDataGrid.Rows[currentCell.Y].Cells["Account"];
cboAccounts.Value = null; //Add this code
cboAccounts.ValueMember = "account_id";
cboAccounts.DisplayMember = "AccountName";
cboAccounts.DataSource = dtAccounts;
int defaultAccountId = (from row in dtAccounts.AsEnumerable()
where row.Field<string>("AccountName").EndsWith("*")
select row.Field<int>("account_id")).FirstOrDefault();
if (defaultAccountId > 0)
cboAccounts.Value = defaultAccountId;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I had the same problem in vb.net .
Not sure if my solution is good, but it works for me.
Briefly: I create a new temporary "DataGridViewComboBoxCell" object, I assign the "DataSource" and the "Value" (which must belong to "DataSource" !!! otherwise the error "value is not valid" comes out) and assign the new object to correct cell in my "DataGridView" main object, like this:
Dim oDataGridViewComboBox As New DataGridViewComboBox With {
.DataSource = MyDataSource
.Value = MyCorrectValueContainedInDataSource
}
oMyDataGridView.Rows(iLineOfComboBox).Cells("ComboBoxColumnName") = oDataGridViewComboBox
The error "value is not valid" is thrown because the ComboBox value is not included among those present in "DataSource".
P.S.: Sorry, I don't know C# ... but the problem is the same, and I have found this post during a search of solution.

How to access some row databound functions in row updating event

I have this code in row data bound event :
if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
string CCC = (string)DataBinder.Eval(e.Row.DataItem, "COLUMN");
DropDownList DropDownList1 = (DropDownList)e.Row.FindControl("DropDownList1");
}
How can I make the code to work in row updating event .
I want to add in rowupdating event only this code without the if condition.
string CCC = (string)DataBinder.Eval(e.Row.DataItem, "COLUMN");
DropDownList DropDownList1 = (DropDownList)e.Row.FindControl("DropDownList1");
Here by Iam showing the sample...for SQL Data Adapter Update...This also I learned from this StackOverFlow only.
private static void OnRowUpdating(object sender, SqlRowUpdatingEventArgs e)
{
string MyERowValu = e.Row["sl_no"].ToString().Trim();
if (e.Row["itm_description"].ToString().Trim().Length == 0)
{
//e.Status = UpdateStatus.SkipCurrentRow;
e.Status = UpdateStatus.SkipAllRemainingRows;
}
}
The Bleow Codes I used in Data_Save Areas...
SQLCon.Open();
blah...blah...blah...blah...
SqlTransaction Trans1 = MyItmDatas.WMSCon.BeginTransaction();
MyDataAdapter1.UpdateCommand.Transaction = Trans1;
MyDataAdapter1.InsertCommand.Transaction = Trans1;
MyDataAdapter1.RowUpdating += new SqlRowUpdatingEventHandler(OnRowUpdating);
MyDataAdapter1.RowUpdating += new SqlRowUpdatingEventHandler(OnRowUpdating);
myDataGrid1.CurrentCell = myDataGrid1.FirstDisplayedCell;
myDataGrid1.EndEdit();
try
{
MyDataAdapter1.Update(ItemTable);
Trans1.Commit();
MessageBox.Show(" ITEMS UPDATED TO ....... ITEM MASTER ", " ITEM MASTER UPDATE ");
}
catch (Exception ex)
{
if (Trans1 != null)
{
Trans1.Rollback();
}
MessageBox.Show(ex.Message, "Item Master Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
SQLCon.Close();
MyDataAdapter1.RowUpdating -= new SqlRowUpdatingEventHandler(OnRowUpdating);
myDataGrid1.Refresh();

Categories