Datagrid View Button repeat - c#

I have added button to datagrid view but when ever the function is called more than once then new button adds I need to stop this addition
void AddtoGrid()
{
try
{
table = new DataTable();
bcol = new DataGridViewButtonColumn();
bcol.HeaderText = "Action ";
bcol.Text = "Delete";
bcol.Name = "deleteUserButton";
bcol.UseColumnTextForButtonValue = true;
table.Columns.Add("Name");
table.Columns.Add("Type");
table.Columns.Add("Status");
table.Columns.Add("Date Created");
table.Columns.Add("Action");
for (int i = 0; i < userAction.UserName.ToArray().Length; i++)
{
row = table.NewRow();
asc.Add(userAction.UserName[i]);
row["Name"] = userAction.UserName[i];
row["Type"] = userAction.UserType[i];
row["Status"] = userAction.UserStatus[i];
row["Date Created"] = userAction.DateCrea[i];
row["Action"] = bcol.Text;
table.Rows.Add(row);
}
UsersView.DataSource = table;
UsersView.AllowUserToAddRows = false;//To remove extra row at the end
UsersView.Columns.Add(bcol);
}
catch (Exception ca)
{
MessageBox.Show(ca.ToString());
}
}//End Function for Getting Present Users

I'm not quite sure I understand your question, though I believe that you need to encapsulate creation of the new column into it's own method and only call it once - in the constructor for instance.
For example:
void CreateDeleteColumn()
{
bcol = new DataGridViewButtonColumn();
bcol.HeaderText = "Action ";
bcol.Text = "Delete";
bcol.Name = "deleteUserButton";
bcol.UseColumnTextForButtonValue = true;
UsersView.Columns.Add(bcol);
}
That should stop it adding a column every time you populate the list view.
Hope this helps and sorry if I misunderstood.
Tony

Related

Select Values from checked DataGridView Items

I have my code as follows:
DataGridViewCheckBoxColumn chk = new DataGridViewCheckBoxColumn();
actGrid.Columns.Add(chk);
chk.HeaderText = "Select";
chk.Name = "select";
chk.ReadOnly = false;
DataGridViewTextBoxColumn mc_no = new DataGridViewTextBoxColumn();
actGrid.Columns.Add(mc_no);
mc_no.HeaderText = "M/C Number";
mc_no.Name = "mc_no";
mc_no.Width = 200;
mc_no.ReadOnly = true;
DataGridViewTextBoxColumn act_name = new DataGridViewTextBoxColumn();
actGrid.Columns.Add(act_name);
act_name.HeaderText = "Name";
act_name.Name = "member";
act_name.Width = 262;
act_name.ReadOnly = true;
while (DR.Read())
{
actGrid.Rows.Add(true, DR.GetInt32(0).ToString(), DR.GetString(2) + " " + DR.GetString(1));
}
Which produces the following output:
And now I want to perform some actions based on which accounts were selected (by toggling the trailing checkboxes), especially M/C Number.
// iterate over DataGridView rows
foreach (DataGridViewRow row in actGrid.Rows)
{
// check, if row is selected by checkbox
if (Equals(row.Cells["select"].Value, true))
{
// get values for selected row
var mc_no_Value = (string)row.Cells["mc_no"].Value;
var member_Value = (string)row.Cells["member"].Value;
// do smth with values here
}
}

Not able to add multiple DataGridViewButtonColumn at runtime

I'm calling a function from another class to a form to load datagridView. when i add only one dataGirdViewButtonColumn its works but when i add two the second one is not added.Another problem i have found is the button is added to empty row..
Function
public void LoadDataGridrcv(DataTable d, DataGridView dg)
{
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
DataGridViewButtonColumn btn1 = new DataGridViewButtonColumn();
if (dg.InvokeRequired)
{
dg.BeginInvoke((MethodInvoker)delegate()
{
dg.Rows.Clear();
dg.ColumnCount = 7;
dg.Columns[0].Name = "Order No.";
dg.Columns[0].Width = 110;
dg.Columns[1].Name = "Order Date";
dg.Columns[1].Width = 100;
dg.Columns[2].Name = "Excepted rcv date";
dg.Columns[2].Width = 100;
dg.Columns[3].Name = "Supplier";
dg.Columns[3].Width = 150;
dg.Columns[4].Name = "Total Items";
dg.Columns[4].Width = 80;
dg.Columns[5].Name = "Total";
dg.Columns[5].Width = 80;
dg.Columns[6].Name = "Status";
dg.Columns[6].Width = 100;
dg.Columns.Add(btn);
btn.HeaderText = "Click to view";
btn.Text = "View";
btn.Name = "btn";
btn.UseColumnTextForButtonValue = true;
btn1.HeaderText = "Click to recieve";
btn1.Text = "Recieve";
btn1.Name = "btn1";
btn1.UseColumnTextForButtonValue = true;
});
foreach (DataRow row in d.Rows)
{
if (dg.InvokeRequired)
{
dg.BeginInvoke((MethodInvoker)delegate() { dg.Rows.Add(row[0].ToString(), row[1].ToString(), row[2].ToString(), row[3].ToString(), row[4].ToString(), row[5].ToString(), row[6].ToString()); });
}
Thread.Sleep(100);
}
}
}
Usage
reatail r = new reatail();
t = new Thread(() => r.LoadDataGridrcv(r.loadAllOrder(), dataGridView1));
t.Start();

How to add rows to a RadGridView in WinForms using c#

I am trying to add a rows to a RadGridView when a use click a button on the form (ie. "Add".)
When the form load I add columns to the RadGridView and make all of them all ReadOnly except one .
When a user click the "Add" button, I want to add a row to this RadGridView. Basically, a user types a UPC code, then I read data from the database and add new row in a grid view with the item name, item price.
Here is what I did to create the columns
private void Register_Load(object sender, EventArgs e) {
GridViewTextBoxColumn UPC = new GridViewTextBoxColumn();
UPC.Name = "UPC";
UPC.HeaderText = "UPC";
UPC.FieldName = "UPC";
UPC.MaxLength = 50;
UPC.TextAlignment = ContentAlignment.BottomRight;
radGridView1.MasterTemplate.Columns.Add(UPC);
radGridView1.Columns["UPC"].Width = 120;
radGridView1.Columns["UPC"].ReadOnly = true;
GridViewTextBoxColumn ItemName = new GridViewTextBoxColumn();
ItemName.Name = "Item Name";
ItemName.HeaderText = "Item Name";
ItemName.FieldName = "ItemName";
ItemName.MaxLength = 100;
ItemName.TextAlignment = ContentAlignment.BottomRight;
radGridView1.MasterTemplate.Columns.Add(ItemName);
radGridView1.Columns["Item Name"].Width = 210;
radGridView1.Columns["Item Name"].ReadOnly = true;
GridViewDecimalColumn QtyColumn = new GridViewDecimalColumn();
QtyColumn.Name = "Qty";
QtyColumn.HeaderText = "Quantity";
QtyColumn.FieldName = "Qty";
QtyColumn.DecimalPlaces = 1;
radGridView1.MasterTemplate.Columns.Add(QtyColumn);
radGridView1.Columns["Qty"].Width = 75;
GridViewMaskBoxColumn PriceColumn = new GridViewMaskBoxColumn();
PriceColumn.Name = "Unit Price";
PriceColumn.FieldName = "UnitPrice";
PriceColumn.HeaderText = "Unit Price";
PriceColumn.MaskType = MaskType.Numeric;
PriceColumn.Mask = "C";
PriceColumn.TextAlignment = ContentAlignment.BottomRight;
PriceColumn.FormatString = "{0:C}";
PriceColumn.DataType = typeof(decimal);
radGridView1.MasterTemplate.Columns.Add(PriceColumn);
radGridView1.Columns["Unit Price"].Width = 75;
radGridView1.Columns["Unit Price"].ReadOnly = true;
GridViewMaskBoxColumn TotalColumn = new GridViewMaskBoxColumn();
TotalColumn.Name = "Total Price";
TotalColumn.FieldName = "TotalPrice";
TotalColumn.HeaderText = "Total Price";
TotalColumn.MaskType = MaskType.Numeric;
TotalColumn.Mask = "C";
TotalColumn.TextAlignment = ContentAlignment.BottomRight;
TotalColumn.FormatString = "{0:C}";
TotalColumn.DataType = typeof(decimal);
radGridView1.MasterTemplate.Columns.Add(TotalColumn);
radGridView1.Columns["Total Price"].Width = 75;
radGridView1.Columns["Total Price"].ReadOnly = true;
}
To add the row Here is what I am doing "when a user click the 'Add' button)
private void ButtonAdd_Click(object sender, EventArgs e) {
string UPC = InputUPC.Text.Trim();
if (UPC.Length < 3) {
return;
}
string sql = " SELECT p.productName, p.price "
+ " FROM products AS p "
+ " WHERE p.productUPC = #upc ";
var parms = new List<MySqlParameter>();
parms.Add(new MySqlParameter("#upc", UPC));
var db = new dbConnetion();
foreach (var i in db.getData(sql, parms, r =>
new ProductsTable() {
_productName = r["productName"].ToString(),
_price = Convert.ToDouble(r["price"])
}
)
) {
//radGridView1.Rows[0].Cells[0].Value = 4.3;
radGridView1.Rows[0].Cells["UPC"].Value = UPC;
radGridView1.Rows[0].Cells["Item Name"].Value = i._productName;
radGridView1.Rows[0].Cells["Qty"].Value = "1";
radGridView1.Rows[0].Cells["Unit Price"].Value = i._price;
radGridView1.Rows[0].Cells["Total Price"].Value = (Convert.ToDouble(i._price) * Convert.ToInt32(radGridView1.Rows[0].Cells["Qty"].Value)).ToString();
}
}
But the add row is giving me an error
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
How can I correctly add rows to the RadGridView when the "Add" button is clicked.
ButtonAdd_Click is wrong because the foreach is always trying to set row 0, which doesn't exist.
You don't specify what GridView you are using, so I can't give specifics, but typically you should be able to call Rows.Add(...).

Why am I getting a DuplicateNameException?

I am currently making a ASP.NET MVC application for users to upload other users to a database from csv and excel.
And while working on the csv-uploader method I have come across a problem where the TextFieldParser - csvReader only reads the first column name and then move on to try and add it to every column in the DataTable and thus it gives the "DuplicateNameException in System.Data.dll".
And I have tried to find a counter that helps against this and i have also changed the delimiter type resulting in every column staying in the first DataTable column instead, meaning that the delimiters is not the problem.
And there is a breakpoint so I could see that the colFields counter manages to find all columns in the csv-file though it only tries to add the first one to the DataTable.
When searching for the problem the only thing I come accross is when there is deliberate code to try and implement the same column over and over, but I do not think that I have anything like that.
The method just stop trying to add the next column and tries to add the same first one instead.
And as a result there is the "DuplicateNameException",
anyone can see why that is?
Here is my code and it is placed in a controller:
[HttpPost]
public ActionResult Import(HttpPostedFileBase file)
{
DataTable csvData = new DataTable();
if (file != null && file.ContentLength > 0)
{
try
{
using (TextFieldParser csvReader = new TextFieldParser(file.InputStream))
{
//TODO:Skapa en lista eller liknande för delimiter val om möjligt.
csvReader.SetDelimiters(new string[] { ";" });
csvReader.HasFieldsEnclosedInQuotes = false;
string[] colFields = csvReader.ReadFields();
foreach (string column in colFields)
{
//TODO:Nuvarande error: DuplicateNameException, den lägger Author title på två olika kolumner och ger exception när detta upptäcks.
DataColumn Titel = new DataColumn(column);
Titel.AllowDBNull = true;
csvData.Columns.Add(Titel);
DataColumn FirstName = new DataColumn(column);
FirstName.AllowDBNull = true;
csvData.Columns.Add(FirstName);
DataColumn LastName = new DataColumn(column);
LastName.AllowDBNull = true;
csvData.Columns.Add(LastName);
DataColumn AbstrNum = new DataColumn(column);
AbstrNum.AllowDBNull = true;
csvData.Columns.Add(AbstrNum);
DataColumn PosterTitel = new DataColumn(column);
PosterTitel.AllowDBNull = true;
csvData.Columns.Add(PosterTitel);
DataColumn Workshop = new DataColumn(column);
Workshop.AllowDBNull = true;
csvData.Columns.Add(Workshop);
DataColumn Keywords = new DataColumn(column);
Keywords.AllowDBNull = true;
csvData.Columns.Add(Keywords);
DataColumn Institution = new DataColumn(column);
Institution.AllowDBNull = true;
csvData.Columns.Add(Institution);
DataColumn CollabEmail = new DataColumn(column);
CollabEmail.AllowDBNull = true;
csvData.Columns.Add(CollabEmail);
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == "")
{
fieldData[i] = null;
}
}
csvData.Rows.Add(fieldData);
}
}
//Fortfarande i try...
SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder();
cb.DataSource="HELMER/SQLEXPRESS";
cb.InitialCatalog="TestDB";
cb.IntegratedSecurity=true;
SqlConnection cnn = new SqlConnection(cb.ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT * FROM csvData", cnn);
cnn.Open();
SqlDataReader rdr=cmd.ExecuteReader();
SqlBulkCopy sbc= new SqlBulkCopy("server=.;database=TestDB;" + "Integrated Security=SSPI");
sbc.DestinationTableName = "Users";
sbc.WriteToServer(rdr);
sbc.Close();
rdr.Close();
cnn.Close();
}
catch (Exception ex)
{
}
}
return RedirectToAction("Index", "Home", new { Message = "The Import was a success" });
}
I have taken some source material from this site:
http://www.morgantechspace.com/2013/10/import-csv-file-into-sql-server-using.html
And also I am still pretty new to this site, though it has been a week right about if there is anything I am doing wrong.
Try this :
foreach (string column in colFields)
{
DataColumn datecolumn = new DataColumn(column);
datecolumn.AllowDBNull = true;
csvData.Columns.Add(datecolumn);
}
Once you created the columns from colFields and you can add rows to the created columns.
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == "")
{
fieldData[i] = null;
}
}
csvData.Rows.Add(fieldData); // Here rows are added to the created columns
}
}

Datagrid View Button repeats

EXACT duplicate of Datagrid View Button
repeat
I have added button to datagrid view but when ever the function is called more than once then new button adds I need to stop this addition
void AddtoGrid()
{
try
{
table = new DataTable();
bcol = new DataGridViewButtonColumn();
bcol.HeaderText = "Action ";
bcol.Text = "Delete";
bcol.Name = "deleteUserButton";
bcol.UseColumnTextForButtonValue = true;
table.Columns.Add("Name");
table.Columns.Add("Type");
table.Columns.Add("Status");
table.Columns.Add("Date Created");
for (int i = 0; i < userAction.UserName.ToArray().Length; i++)
{
row = table.NewRow();
asc.Add(userAction.UserName[i]);
row["Name"] = userAction.UserName[i];
row["Type"] = userAction.UserType[i];
row["Status"] = userAction.UserStatus[i];
row["Date Created"] = userAction.DateCrea[i];
table.Rows.Add(row);
}
UsersView.DataSource = table;
UsersView.AllowUserToAddRows = false;//To remove extra row at the end
UsersView.Columns.Add(bcol);
}
catch (Exception ca)
{
MessageBox.Show(ca.ToString());
}
}//End Function for Getting Present Users
Split the method up in two:
1.) To setup the grid structure
2.) To add new rows
public void SetupDataGridView()
{
table = new DataTable();
bcol = new DataGridViewButtonColumn();
bcol.HeaderText = "Action ";
bcol.Text = "Delete";
bcol.Name = "deleteUserButton";
bcol.UseColumnTextForButtonValue = true;
table.Columns.Add("Name");
table.Columns.Add("Type");
table.Columns.Add("Status");
table.Columns.Add("Date Created");
UsersView.DataSource = table;
UsersView.AllowUserToAddRows = false;//To remove extra row at the end
UsersView.Columns.Add(bcol);
}
public void PopulateDataGridView()
{
for (int i = 0; i < userAction.UserName.ToArray().Length; i++)
{
row = table.NewRow();
asc.Add(userAction.UserName[i]);
row["Name"] = userAction.UserName[i];
row["Type"] = userAction.UserType[i];
row["Status"] = userAction.UserStatus[i];
row["Date Created"] = userAction.DateCrea[i];
table.Rows.Add(row);
}
}
And this is still a suboptimal approach, but that's the most anyone can do for someone with your skills.
You lack basic knowledge of programming and object oriented programming in particular. Get a book (e.g. chris sells' book on windows forms programming) read it, and then come back. You will benefit from it!

Categories

Resources