How to add new row on click winforms - c#

I have a winforms application that I am developing, I have hit a dead end. What I am trying to do is on each "click", add a new row to my DataTable with the values input in the form. This Datatable is the DataSource for my DataGridView. Can someone point me in the right direction on how this can be achieved.
Articles I looked at:
How to add new row to datatable gridview
My code:
private void btnAdd_Click(object sender, EventArgs e)
{
//inserting into order table
DataTable dt = new DataTable();
string articleId = cmbArticle.Text;
string productDescription = txtDesc.Text;
string type = txtType.Text;
string materialType = txtMaterial.Text;
string size = cmbSizes.Text;
string quantity = txtQuantity.Text;
try
{
dt.Columns.Add("Article");
dt.Columns.Add("Description");
dt.Columns.Add("Type");
dt.Columns.Add("Material");
dt.Columns.Add("Size");
dt.Columns.Add("Quantity");
dt.Columns.Add("DateTime");
DataRow dr = dt.NewRow();
//addrows
dr["Article"] = articleId;
dr["Description"] = productDescription;
dr["type"] = type;
dr["Material"] = materialType;
dr["Size"] = size;
dr["Quantity"] = quantity;
dt.Rows.Add(dr);
dgvView.DataSource = dt;
}
catch (Exception ex)
{
}
}

On each click you are creating a new DataTable which would be with just one row, You need to create DataTable once and then just keep adding rows to in the click. Define your DataTable at class level and then in your event just add a new row to it.
DataTable dt = new DataTable(); //at class level
private void Form1_Load(object sender, EventArgs e)
{
CreateDataTableColumns();
//.... your code
}
Then have a method to create table structure, call that method once from your From_Load event.
private void CreateDataTableColumns()
{
dt.Columns.Add("Article");
dt.Columns.Add("Description");
dt.Columns.Add("Type");
dt.Columns.Add("Material");
dt.Columns.Add("Size");
dt.Columns.Add("Quantity");
dt.Columns.Add("DateTime");
}
Later add rows to your class level DataTable in Add event.
private void btnAdd_Click(object sender, EventArgs e)
{
string articleId = cmbArticle.Text;
string productDescription = txtDesc.Text;
string type = txtType.Text;
string materialType = txtMaterial.Text;
string size = cmbSizes.Text;
string quantity = txtQuantity.Text;
try
{
DataRow dr = dt.NewRow();
//addrows
dr["Article"] = articleId;
dr["Description"] = productDescription;
dr["type"] = type;
dr["Material"] = materialType;
dr["Size"] = size;
dr["Quantity"] = quantity;
dt.Rows.Add(dr);
dgvView.DataSource = dt;
}
catch (Exception ex)
{
}
}
(I believe you are doing something with the exception object in your catch block, like logging, showing message to user etc)

Related

how to filter a column in datagridview imported from excel file

For example I have a datagridview1 with data imported from a excel file and there are 12 columns: date, Name, Activity, Project,time, comment,ect. and 1000 row.
What I want to do is to filter only all with the Project name in project column.
for example I have support as a (Projectname) I want to show all columns filtyring by support rows.
I have combobox to select which column I need to filter it( e.g Project) here,
I tried with this code but it dose not work.
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string projektItem = comboBox1.Items[comboBox1.SelectedIndex].ToString();
if (projektItem == "Project") {
foreach (DataRow dataRow in dataGridView1.Rows)
{
StringBuilder filter = new StringBuilder();
for (int i = 0; i < dataGridView1.Columns.Count - 1; i++)
{
filter.Append(dataRow[i].ToString());
filter.Append("\t");
}
dataGridView1.DataSource = filter.ToString();
}
if (projektItem == "Name") {
}
if (projektItem == "Aktivity") {
}
}
This is how I do it. convert datagridview to datatable
And this is func for filter purpose:
Hold the origin table to go back if you turn your filter off
//datagrid to datatable
DataTable datatable = new DataTable();
datatable = (DataTable)dataGridView1.DataSource;
//datatableOrigin to hold your origin table
DataTable originTable = null;
// find Function
Public void Find(string column, string st)
{
DataRow[] dtResult;
DataTable holder = New DataTable;
//get datatable Schema
DataTable holder = datatable.Clone();
holder.Rows.Clear();
If (originTable != null)
datatable = originTable;
Else
originTable = datatable;
//select return datarow array
dtResult = datatable.Select("[" + column + "] LIKE '%" + st + "%'");
//import all your result into holder
foreach(DataRow dr In dtResult){holder.ImportRow(dr);}
//pass from holder to datatable
datatable = holder.Copy();
holder.Clear();
}
public void showDT()
{
dataGridView1.DataSource = datatable;
}
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// choose your column here
}
private void btn_Clicked(object sender, EventArgs e)
{
Find('YourColumn, 'your search string);
showDT();
}

How to add control cells programmatically in a gridview C# .net?

Every row have to has a dropdownlist and a submit button.
So I made a List for data.
I added them like this.
enter image description here
//In my code behind
List<data> listdatainfo = new List<data>();
protected void Button1_Click(object sender, EventArgs e){
SqlDataReader detaillist = comm2.ExecuteReader();
while (detaillist.Read())
{
rmainfo tempinfo = new rmainfo();
tempinfo.itemdetail= detaillist["itemdetail"].ToString();
tempinfo.creditmemo= detaillist["creditmemo"].ToString();
tempinfo.submit= "0";//it will be filled 0 or 1
listdatainfo .Add(tempinfo);
}
loadDataTable();}
//it was referenced from here http://asp.net-informations.com/gridview/without-database.htm
private void loadDataTable()
{
DataSet ds = new DataSet();
DataTable dt;
dt = new DataTable();
DataColumn itemdetail;
DataColumn creditmemo ;
CommandField submit = new CommandField();
submit.EditText = "Edit";
submit.ShowEditButton = true;
itemdetail= new DataColumn("itemdetail",Type.GetType("System.String"));
creditmemo = new DataColumn("creditmemo ",Type.GetType("System.String"));
submit = new CommandField();
dt.Columns.Add(itemDetail);
dt.Columns.Add(creditMemo);
dt.Columns.Add("submit"); //it's for submit button
foreach (data tempinfo in listdatainfo )
{
DataRow dr;
dr = dt.NewRow();
dr["Item Detail"] = tempinfo.itemDetail;
dr["Credit Memo"] = tempinfo.creditMemo;
dr["submit"] = submit;
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
GridView2.DataSource = ds.Tables[0];
GridView2.DataBind();
}}
public class data
{
public string itemDetail { get; set; }
public string creditMemo { get; set; }
public string submit { get; set; }
}
As i expected, this line occured an error this line.
dr["submit"] = submit;
How can i add a button each row? or any component?
It was easier in classic asp.....
Please help.
You have to add the buttons in the GridView model instead of the datatable that is feeding it.

losing data entered in dataview C#

I am using Visual C# 2008 to make a application that takes the data from textboxes and displays it in datagridview in another form the conforming make it entered to the database.
I send the data using dataTable with a function entered the data without any symentic error but when I call the other for the datagridview comes empty and the database comes empty. When I duplicate a primary key it gives an error stating "cannot duplicate primary key".
This is the code for the function that transfers that datatable
public DataTable showout() {
DataTable dtab = new DataTable();
DataColumn dc1 = new DataColumn("رقم المتسلسل");
DataColumn dc2 = new DataColumn("رقم الحساب");
DataColumn dc3 = new DataColumn("أسم الحساب");
dtab.Columns.Add(dc1);
dtab.Columns.Add(dc2);
dtab.Columns.Add(dc3);
// Create an array for the values.
object[] newRow = new object[3];
// Set the values of the array.
string s = numb.Text;
newRow[0] =numb.Text;
newRow[1] = textBox5.Text;
newRow[2] =note.Text;
DataRow row;
dtab.BeginLoadData();
// Add the new row to the rows collection.
row = dtab.LoadDataRow(newRow, true);
return dtab;
}
this is the code that I call the function in the other From
private void Cashagree_Load(object sender, EventArgs e) {
dataGridView1.DataSource = ch.showout();
}
the second datagrid entering function its in the same class
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.Visible = true;
dataGridView1.DataSource = showout();
entering(true);
}
and this is the entering to the database
public void entering(bool bl)
{try{
if (bl)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
DateTime Date = DateTime.Today;
SqlCommand cmd = new SqlCommand("INSERT INTO Accont(Account_ID,Account_Name,Owners,Curency,Curncytype,Depet,Credet_devet,Date,Note) VALUES (#AccountID, #AccountName, #Owner, #Curncy,#Curncytype,#Depet,#Cridetdevet,#Date,#Note)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#AccountID",numb.Text);
cmd.Parameters.AddWithValue("#AccountName", comboBox1.SelectedText.ToString());
cmd.Parameters.AddWithValue("#Owner", owner.Text);
cmd.Parameters.AddWithValue("#Curncy", curency.Text);
cmd.Parameters.AddWithValue("#Curncytype", curncyval.Text);
cmd.Parameters.AddWithValue("#Depet", Depet.Text);
cmd.Parameters.AddWithValue("#Cridetdevet", textBox5.Text);
cmd.Parameters.AddWithValue("#Date", Date);
cmd.Parameters.AddWithValue("#Note", note.Text);
connection.Open();//Owner
cmd.ExecuteNonQuery();}}
}
catch(Exception ee)
{MessageBox.Show(ee.Message);}
the conforming from the another form
private void button1_Click_1(object sender, EventArgs e)
{
ch.entering(true);
Close();
}
Instead of using the dtab.LoadDataRow, you should be using the dtab.Rows.Add(datarow) method.
An example of how to do this:
public DataTable showout()
{
DataTable dtab = new DataTable();
// More efficient way of adding the columns with types:
dtab.Columns.Add("رقم المتسلسل", typeof(String));
dtab.Columns.Add("رقم الحساب", typeof(String));
dtab.Columns.Add("أسم الحساب", typeof(String));
/*
DataColumn dc1 = new DataColumn("رقم المتسلسل");
DataColumn dc2 = new DataColumn("رقم الحساب");
DataColumn dc3 = new DataColumn("أسم الحساب");
dtab.Columns.Add(dc1);
dtab.Columns.Add(dc2);
dtab.Columns.Add(dc3);
*/
// Create a new row using the .NewRow method
DataRow datRow = dtab.NewRow();
datRow["رقم المتسلسل"] = numb.Text;
datRow["رقم الحساب"] = textBox5.Text;
datRow["أسم الحساب"] = note.Text;
// Add the new row to the DataTable
dtab.Rows.Add(datRow);
return dtab;
}
Reference:
How to: Add Rows to a DataTable
Adding Data to a DataTable
In solve it by the sending the DataTable dt from the first Form cash to the second Form cashagree as a prameter by calling the method that return datagridview
in cash form I wrote this:
cashagree gc2 = cashagree(showout());
in cashagree form I wrote this
DataTable dt = new DstsTsble();
public cashagree(DataTable d2){
dt =d2;
}
and in the load of `cashagree_Load` I asign the datagridview datasoure
private void Cashagree_Load(object sender, EventArgs e)
{
if (dt.Rows[0].IsNull(dt.Columns[0]))
{
MessageBox.Show("There no primary key");
Close();
}
dataGridView1.DataSource = dt;
dataGridView1.Columns[7].Visible = false;// Iwantn't all the datatable so I diapple some Columns
dataGridView1.Columns[5].Visible = false;
dataGridView1.Columns[7].Visible = false;
dataGridView1.Columns[6].Visible = false;
dataGridView1.Columns[4].Visible = false;
}

updating datatable from gridview updating event

I have a datatable that I am populating with data, however if I want to edit the row I am getting an error
Unable to cast object of type 'System.Web.UI.WebControls.DataControlLinkButton' to type 'System.Web.UI.WebControls.TextBox'.
The code that populates the gridview is
public void addTochkout(string type, string no)
{
DataTable dt = (DataTable)Session["table_chkout"];
DataRow dr = dt.NewRow();
dr[0] = type;
dr[1] = no;
dt.Rows.Add(dr);
Session["table_detail"] = dt; //save dt to new session
gridbind();
}
public void gridbind()
{
//gridview
if (Session["table_detail"] != null)
{
DataTable dt = (DataTable)Session["table_detail"];
if (dt.Rows.Count > 0)
{
chkoutDetail.DataSource = dt;
chkoutDetail.DataBind();
string countitems = dt.Rows.Count.ToString();
Session["cart_counter"] = countitems;
}
}
else
{
chkoutDetail.DataSource = null;
chkoutDetail.DataBind();
}
}
Now, when I try and update the gridview I am getting the error above from the line
dt.Rows[row.DataItemIndex]["TicketType"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
The entire code block where is erroring is
protected void TaskGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = (DataTable)Session["table_detail"];
//Update the values.
GridViewRow row = chkoutDetail.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["TicketType"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Price"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
//Reset the edit index.
chkoutDetail.EditIndex = -1;
//Bind data to the GridView control.
gridbind();
}
I would be very grateful if you could help me solve this issue.
Simon
Note that when you have the Edit option enabled, the first and second cells of the edit mode of the row in the grid view are linkbuttons(Update and Cancel). So probably you have to change the index while getting the textbox in the row
//Cell number 2 for the first textbox. 0 for update link and 1 for cancel link
dt.Rows[row.DataItemIndex]["TicketType"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
I had figured out my issue just after posting the, but it wouldn't allow me to answer the question.
heres my solutions
protected void TaskGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
// //Update the values.
string type = e.NewValues[0].ToString();
string qty = e.NewValues[1].ToString();
//Retrieve the table from the session object.
DataTable dt = (DataTable)Session["table_detail"];
dt.Rows[e.RowIndex]["TicketType"] = type;
dt.Rows[e.RowIndex]["TicketNo"] = qty;
dt.AcceptChanges();
chkoutDetail.EditIndex = -1;
//Bind data to the GridView control.
gridbind();
int value1 = Convert.ToInt32(ddtickettype.SelectedItem.Value);
int value2 = Convert.ToInt32(ddTicketno.SelectedItem.Value);
string tType = ddtickettype.SelectedItem.Text;
string tNo = ddTicketno.SelectedItem.Text;
int prevTotal = Convert.ToInt32(lblAmount.Text);
int total = (value1 * value2) + prevTotal;
Session["TotalAmount"] = total.ToString();
if (Session["TotalAmount"] != null)
{
lblAmount.Text = Session["TotalAmount"].ToString();
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
}

How to get Value of specific cell of datagridview in Winform application

I have a dataGridView which contains the check-boxes in its first column. Now as per my requirement i have to get the value of Employee No column for the row whose checkbox has been clicked on another button click event.Also how to get the value for multiple checkbox selected .
Here is my code..
private void btn_load_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Select", System.Type.GetType("System.Boolean"));
dt.Columns.Add("Employee No");
dt.Columns.Add("Employee Name");
dt.Columns.Add("Join Date");
DataRow dr;
for (int i = 0; i <= 10; i++)
{
dr = dt.NewRow();
dr["Select"] = false;
dr["Employee No"] = 1000 + i;
dr["Employee Name"] = "Employee " + i;
dr["Join Date"] = DateTime.Now.ToString("dd/MM/yyyy");
dt.Rows.Add(dr);
}
dataGridView1.AllowUserToAddRows = true;
dataGridView1.AllowUserToDeleteRows = true;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView1.DataSource = dt;
}
private void btn_Click(object sender, EventArgs e)
{
//I need the Employee Id values here
}
Please help me .Thanks in advance..
You can also use the DataSource property:
private void btn_Click(object sender, EventArgs e)
{
int[] employeeIds = (dataGridView1.DataSource as DataTable).Rows
.Cast<DataRow>()
.Where(r => (bool)r["Select"])
.Select(r => Convert.ToInt32(r["Employee No"]))
.ToArray();
}
and use the System.Linq namespace.
Because you have bound your DataTable to the grids DataSource, you could make dt a class variable and use that to check the selected ones.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private DataTable dt;
private void btn_load_Click(object sender, EventArgs e)
{
dt = new DataTable();
dt.Columns.Add("Select", System.Type.GetType("System.Boolean"));
dt.Columns.Add("Employee No");
dt.Columns.Add("Employee Name");
dt.Columns.Add("Join Date");
DataRow dr;
for (int i = 0; i <= 10; i++)
{
dr = dt.NewRow();
dr["Select"] = false;
dr["Employee No"] = 1000 + i;
dr["Employee Name"] = "Employee " + i;
dr["Join Date"] = DateTime.Now.ToString("dd/MM/yyyy");
dt.Rows.Add(dr);
}
dataGridView1.AllowUserToAddRows = true;
dataGridView1.AllowUserToDeleteRows = true;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView1.DataSource = dt;
}
private void btn_Click(object sender, EventArgs e)
{
//I need the Employee Id values here
foreach (DataRow row in dt.Rows)
{
if ((bool)row["Select"] == true)
{
}
}
}
}
Suppose to have a global variable in your form class declared as
List<int> empIDs = new List<int> empIDs();
Now in your click event you could write
private void btn_Click(object sender, EventArgs e)
{
empIDs.Clear();
foreach(DataGridViewRow r in dgv.Rows)
{
DataGridViewCheckBoxCell c = r.Cells["Select"] as DataGridViewCheckBoxCell;
if(Convert.ToBoolean(c.Value))
empIDs.Add(Convert.ToInt32(r.Cells["Employee No"].Value));
}
}
At the end of the click event the global variable will be filled with the ID of the employees that have their SELECT cell clicked

Categories

Resources