N
N
Nikita Salnikov2020-05-05 21:05:59
C++ / C#
Nikita Salnikov, 2020-05-05 21:05:59

Error when adding a new line with the same name?

5eb1a598641c8052288470.jpeg

Hello. There is such a table. made a button to add a new row in the given table when the program starts. An error occurs when adding a new line with the same name. how to fix? And is it possible to do something so that when adding a new line, when entering in the line "Type - Income", it is automatically recognized as an already existing type and the "Amount" of the new line is automatically added to one of the lines from the same lines?

private void AddBtn_Click(object sender, EventArgs e)
        {
            
            Form1 main = this.Owner as Form1;
            if (main != null)
            {
                DataRow nRow = main.база_данныхDataSet.Tables[0].NewRow();
               int rc = main.база_данныхDataSet.RowCount + 1;
                nRow[0] = rc;
                nRow[1] = tbType.Text;
                nRow[2] = tbCategory.Text;
                nRow[3] = tbDate.Text;
                nRow[4] = Convert.ToInt32(tbSum.Text);
                nRow[5] = tbTotal.Text;
                nRow[6] = tbComments.Text;
                main.база_данныхDataSet.Tables[0].Rows.Add(nRow);
                main.accountingTableAdapter.Update(main.база_данныхDataSet.Accounting);
                main.база_данныхDataSet.Tables[0].AcceptChanges();
                main.dataGridView1.Refresh();
                tbType.Text = " ";
                tbCategory.Text = "";
                tbDate.Text = "";
                tbSum.Text = "";
                tbTotal.Text = "";
                tbComments.Text = "";
                
               
            }
        }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
Collin, 2020-05-06
@Collin

Loading data:
First, we will create two global fields (it is possible and better to do this through a property, but we will do it simpler)

DataSet dataSet = new DataSet();
string filePath = Application.StartupPath + "\\dataset.xml";

private void Form1_Shown(object sender, EventArgs e)
{
  // Проверяем наличие файла, если на месте, то загружаем из него наш dataSet
  if (File.Exists(filePath))
  {
    dataSet.ReadXml(filePath);
  }
  // Если отсутствует, создадим файл с простой структурой для 1 строки
    else
  {
    using (XmlWriter writer = XmlWriter.Create("dataset.xml"))
    {
            writer.WriteStartElement("Data");
            writer.WriteStartElement("rows");
            writer.WriteElementString("Type", "");
            writer.WriteElementString("Category", "");
            writer.WriteElementString("Date", "" + DateTime.Now.ToString("dd.mm.yyy") + "");
            writer.WriteElementString("Summ", "0");
            writer.WriteElementString("Total", "0");
            writer.WriteElementString("Comment", "");
            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.Flush();
    }
  }
  // Заполняем датагрид
  DataGridFill(dataSet);
  //Подписываемся на событие добавление новой строки
  dataGridView1.RowsAdded += new DataGridViewRowsAddedEventHandler(RowsAdded);
}

If we did not have a file, the program will create a file with 1 line with the following structure:
<?xml version="1.0" standalone="yes"?>
<Data>
  <rows>
    <Type />
    <Category />
    <Date>06.03.2020</Date>
    <Summ>0</Summ>
    <Total>0</Total>
    <Comment />
  </rows>
</Data>

Next, the method of adding a new row:
We can do something not very cool and add an empty row directly to the grid:
private void Add_button_Click(object sender, EventArgs e)
{
  string empty = "";
  string date = DateTime.Now.ToString("dd.mm.yyyy");

  if (dataGridView1.Columns.Count != 0)
  {
    dataSet.Tables[0].Rows.Add(new object[] { empty, empty, date, empty, empty, empty });
    dataGridView1.Update();
  }
  else
    MessageBox.Show("Ошибка: Невозможно добавить строку в таблицу, в которой отсутствуют колонки",
            "Ошибка",
            MessageBoxButtons.OK,
            MessageBoxIcon.Error);
}

And we can make it more convenient and call a window where we enter / select the data we need.
You can calculate the amount both at startup, running in a loop, and when processing the dataGridView1.RowsAdded event, which we subscribed to after filling the grid:
dataGridView1.RowsAdded += new DataGridViewRowsAddedEventHandler(RowsAdded);

For example -- at startup I format the grid a bit and do this thing:
private void DataGridFill(DataSet dataSet)
{
  if (dataSet != null)
  {
        dataGridView1.DataSource = dataSet.Tables[0];
    
    for(int i = 0; i < dataSet.Tables[0].Rows.Count; i++)
    {
      if (string.IsNullOrEmpty(dataSet.Tables[0].Rows[i][4].ToString()))
            ataSet.Tables[0].Rows[i][4] = 0;
        }

    for (int i = 0; i < dataSet.Tables[0].Rows.Count; i++)
    {
      if (i != 0 && !string.IsNullOrEmpty(dataSet.Tables[0].Rows[i][3].ToString()))
        dataSet.Tables[0].Rows[i][4] = Convert.ToDouble(dataSet.Tables[0].Rows[i - 1][4]) + Convert.ToDouble(dataSet.Tables[0].Rows[i][3]);
      else if (!string.IsNullOrEmpty(dataSet.Tables[0].Rows[i][3].ToString()))
        dataSet.Tables[0].Rows[i][4] = dataSet.Tables[0].Rows[i][3];
    }
    }

    dataGridView1.Columns[0].HeaderText = "Тип";
    dataGridView1.Columns[1].HeaderText = "Категория";
    dataGridView1.Columns[2].HeaderText = "Дата";
    dataGridView1.Columns[3].HeaderText = "Сумма";
    dataGridView1.Columns[4].HeaderText = "Итого";
    dataGridView1.Columns[5].HeaderText = "Комментарий";
}

But it considers strictly the amount, not taking into account the expense/income tag. What would take into account, you need to check the cell with the type and, based on this, already perform mathematical operations.

V
Vladimir Korotenko, 2020-05-05
@firedragon

Programming is pretty boring.
You describe an action and translate it from a human language into a programming language you know.
Ideally, you have a TK and you stupidly insert constructions.
In your case, you need to go to the description of this control and study its "Life cycle"
In simple terms, when you add it, it creates a bunch of events, you select the one you need and execute the code you need in it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question