I have a usersdataTable with an "Code" column I set as PK and auto-increment "true" in MySql DB.
I want users to fill in values for first name, last name, username etc on a datagrid view but cannot enter the Code value.
I have this code for update/insert:
private void usersBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
try
{
if (dgvUsers.RowCount > 0)
{
for (int i = 1; i <= dgvUsers.RowCount; i++)
{
var code = dgvUsers.Rows[i].Cells[0].Value.ToString();
if (code == string.Empty)
{
// add users
this.usersTableAdapter.Insert(
dgvUsers.Rows[i].Cells[1].Value.ToString(),
dgvUsers.Rows[i].Cells[2].Value.ToString(),
dgvUsers.Rows[i].Cells[3].Value.ToString(),
GlobalClass.MD5Hash(dgvUsers.Rows[i].Cells[4].Value.ToString()),
DateTime.Now,
null
);
}
else
{
// edit users
this.usersTableAdapter.Update(this.eko_payrollDataSet.users);
}
}
}
MessageBox.Show("Details Updated Successfully");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Table Structure:
Code int NN PK Autoincrement
firstName Varchar NN
lastName Varchar NN
userName Varchar NN
password varchar NN
created datetime NN
modified datetime Null?
I dragged the datagridview to the form from a dataset that created a binding source. When I press the + button to add a new row and when finished entering the values, I get a NoNullAllowedExeption for column Code when I move the cursor to another row or attempt to add a row below this.
What do I need to do to fix this? I have not added validation code that would cause this.
I have seen the same problem I am experiencing here http://www.databaseforum.info/5/857494.aspx
When your PK is an auto-increment column, the associated column in the DataSet should have its proper AutoIncrement and AutoIncrementSeed, if not you should be able to set them in the dataset designer.
Here is an issue similar to yours, look if you can find something useful.
autoincrement-values-in-autogenerated
I think there is little about your problem, can you put an example or put all the properties of the dataset/datatable and gridview.
Good luck.
Related
I'm working on a Windows Forms project and I have some data in a XtraGrid.GridControl with these columns:
ID, Description, To Process
I'm loading these data from database, and the column To Process contains a boolean field.
I would like to have instead of the current 1 and 0 values a checkbox, that will be checked if the value is 1 and unchecked if the value is 0.
How can I achieve this with Dev Express 16?
This is what I did so far:
imported a DevExpress.XtraGrid.GridControl in my form Design;
added three columns ID, Description and To Process;
populated the GridControl DataSource from code behind with this method:
private void LoadTableData()
{
// initialization
gcTable.DataSource = null;
string query = " SELECT id, description, to_process FROM test_table ";
DataTable dt = Utils.ExecuteQuery(query);
if (dt != null && dt.Rows.Count > 0)
{
gcTable.DataSource = dt;
}
}
As now, I have my table populated but with 1 and 0 values in the column To Process.
Assign a RepositoryItemCheckEdit to your To Process column's ColumnEdit property and set its ValueChecked and ValueUnchecked properties if necessary. More information here.
You can use gridView1_CustomRowCellEdit event to change repository for a cell of grid view. If data column is type of bool, cells of grid control will be check boxes.
dt.Columns["to_process"].DataType = typeof(bool);
Here is a sample code for CustomRowCellEdit event.
void gridView1_CustomRowCellEdit(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e)
{
if (e.Column.FieldName == "to_process")
{
DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit repChk = new DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit();
e.RepositoryItem = repChk;
}
}
I'm creating a windows form that will allow my group at work to check in & out computers from our spare cabinet. I have two tables, an 'Assets' table & Inventory Log table. The user will fill out the GUI and select the asset they want from the check out screen. The problem I am having is trying to pass the foreign key 'InventoryID' to the log table. I have the main textbox's bound to datagrid cells but I am unable to do this with the inventory ID because I have it bound to a textbox so the user does not have to enter it every time.
I have tried creating an insert query that takes the textbox and converts it to int and then inserts it into the method but it catches an exception. Note, this query works when I test it in the query builder. I have also tried adding it with the binding source property but it cant find the index.
private void BtnSubmit_Click(object sender, EventArgs e)
{
//get asset number
string asset = txtAssetNumber.Text;
//get invID from textbox
int InventoryID = Convert.ToInt32(txtinv.Text);
//this query changes available status to 'No'
inventoryTableAdapter.SetNo(asset);
//runs query to determine what rows have 'Yes'
inventoryTableAdapter.Available(this.loanerCabDataSet.Inventory);
try
{
//add new row to log table
inventoryLogBindingSource.AddNew();
//suppose to insert the ID into table
inventoryLogTableAdapter.insertinvid(InventoryID);
//set textbox back to today's date
txtOutDate.Text = DateTime.Today.ToString("MM/dd/yyyy");
this.Validate();
this.inventoryBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.loanerCabDataSet);
MessageBox.Show("Success");
}
catch (Exception)
{
throw;
}
}
Query:
INSERT INTO InventoryLog (InventoryID)
VALUES (?)
Finally figured out a way around it.
Created insert query and instead of binding all of the textboxes to the column, I created variables and passed them into the function.
Heres what it looks like now.
inventoryLogTableAdapter.Insert(InventoryID, customer, tech, loaneddate, datein, location, ticket, notes);
I have a dataGridView in which I can insert, delete and update values but something is bothering me.
The user can only modify the 2 columns that are displayed (size and quantity), 2 others are hidden (ID and chosenComponent).
ID is PK in my table.
This is what I did to set ID and chosenComponent of new rows :
private void dataGridViewStock_DefaultValueNeeded(object sender,
System.Windows.Forms.DataGridViewRowEventArgs e)
{
e.Row.Cells["id"].Value = "1";
e.Row.Cells["codeArticleComponent"].Value = labelComponentChosen.Text;
}
Whatever value I put for the ID, the first available number will be inserted to the database. It works but I'm afraid it might later cause bugs.
Is there a better way to achieve this ? Or can I leave it as is ?
You may need a separate column(Only in the GirdView) to identify whether the current row is newly added or existing one. And increment id column with negative values based on the new column.
While saving the data you can identify the newly created rows, based on that you can save the data by inserting without id column or update the existing data.
Hope this clarifies you.
This is my code for the auto-increment primary key in a datagrid view
private void Row_Added(object sender,
DataGridViewRowsAddedEventArgs e){
foreach(DataGridViewRow dtr in dataGridView1.Row){
dataGridView1.Rows[e.RowIndex-1].Cells[0].Value =
e.RowIndex;
}
}
i used this...
I try to develop a program for insert datas from excel table to SqlServer.
I had an error when I try to insert data to sqlserver. That is my error message here
"Cannot insert duplicate key row in object 'dbo.ta_Kullanici' with
unique index 'IX_ta_Kullanici'.\r\nThe statement has been terminated."
ID is unque and autoincrement In my table.
Thanks for your help! :)
A part of my code is here;
if (!check)
{
kul = new ta_Kullanici();
hata = new KullaniciHata();
hata.AdSoyad = kullanicilar.Rows[i][7].ToString() + " " + kullanicilar.Rows[i][8].ToString();
hatalar.Add(hata);
kul.kul_ad = kullanicilar.Rows[i][7].ToString();
kul.kul_soyad = kullanicilar.Rows[i][8].ToString();
foreach (var bolge in bolgeler)
{
if (kullanicilar.Rows[i][1].ToString().ToLower().IndexOf(bolge.bolge_ad.ToLower()) != -1)
{
kul.kul_bolge_Id = bolge.bolge_Id;
}
}
kul.kul_ikTar = DateTime.Now;
kul.kul_statu = true;
kul.kul_guid = Guid.NewGuid().ToString();
kul.kul_ikIP = "127.0.0.1";
kul.kul_ik_kul_Id = 5;
kul.kul_TCKNo = kullanicilar.Rows[i][9].ToString();
kul.kul_kulAd = kullanicilar.Rows[i][6].ToString();
kul.kul_tip_enm = 2;
if (!string.IsNullOrWhiteSpace(kullanicilar.Rows[i][9].ToString()))
{
kul.kul_sifre = kullanicilar.Rows[i][9].ToString();
}
else
{
kul.kul_sifre = "123123";
}
checkList.Add(kul);
db.ta_Kullanici.Add(kul);
db.SaveChanges();
hatalar.Remove(hata);
}
Have a look at the table in question dbo.ta_Kullanici and see what column the index named IX_ta_Kullanici is on.
The index in question is a unique index, meaning that it will not allow any duplicate values for the column(s)
Remember that this index could be on any column in the table and is not limited to the Primary Key.
So basically the issue is that the column has an index of Unique key and what that index does is that it makes sure duplicate values do not get repeated on the column, to change that what you can do is to go to Management studio, go to the table that has that column, right-click on the column and click to modify. A screen will appear with all the columns displayed. right-click the small box beside the column and select indexes/keys. Then you will see a IsUnique property. set it to 'NO'.
A person can have many bills.
Each bill can have many (Item, Quantity) entries.
My primary key is (Bill_No,Item_Code) .
For each Bill_no, I can enter a particular Item_Code only once.
I enter the (Item,Quantity) details via a Grid View as shown.
Can I validate this at the front end on Create Indent click so that an Item_no entered once in the gridView cannot be entered again before submit is clicked?
I have done the back end primary key validation in the Data Access Layer. It just ignores the duplicate Item_No and continues with an alert.
I want to check for duplicate Item_code entries row-wise via front end so no data is lost on create.
//to check repeated item in the gridview
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
if (dtCurrentTable.Rows.Count > 1)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count-1; i++)
{
if (dtCurrentTable.Rows.Count > 1)
{
TextBox prevItem = (TextBox)Grid_ItemList.Rows[rowIndex].Cells[1].FindControl("itemCode");
if (prevItem.Text == itemcode && currentRow.RowIndex != rowIndex)
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation1", "<script language='javascript'>alert('Item Alredy Added, Please change the Qty if needed.')</script>");
txt.Text = "";
qtyl.Enabled = false;
return;
}
}
rowIndex++;
}
}
SetRowData();
}
put this code inside your dropdownlist onselected index change function, just before you populate the itemcode.
Even if you'd check it against the data in your grid it would be possible that paging is enabled. Then the grid only stores the data of the current page.
Apart from that, even without paging you'll have the problem that another user could add a record at the same time with the same Bill_no+Item_Code.
So there is no other/better way than to handle the constraint exception of the database. Therefore you need to add an unique index on the combination of Bill_no+Item_Code.
Assuming SQL-Server as rdbms, you can use the SqlException's Number property:
string error = "";
try
{
CreateIndent();
} catch (SqlException ex)
{
switch (ex.Number)
{
case 2627: // Unique Index/ Primary key Violation/ Constraint Violation
case 2601: // Unique Index/Constraint Violation
error = "Bill_no and Item_Code are not unique";
break;
default:
error = "Unknown SQL-Exception";
break;
}
}
// show error
Update
Suppose I enter (Apple,10) , (Apple,20) and (Apple,40) as three items
of my gridview, my only option is to have (Apple,10) enter the
database and the other entries error out?
string
unique=((TextBox)Grid_ItemList.Rows[rowIndex].Cells1.FindControl("itemCode")).ToString();
This is how I get my data in each row. Now how do I check for
uniqueness?
If you insist on checking the GridView row by row which won't work with paging or if another user uses this page simultaneously, this should work:
var allItems = Grid_ItemList.Rows.Cast<GridViewRow>()
.GroupBy(r => new {
ItemValue = ((DropDownList)r.FindControl("DdlItemName")).SelectedValue,
ItemCode = ((TextBox) r.FindControl("itemCode")).Text.Trim()
});
var duplicates = allItems.Where(g => g.Count() > 1);
// show somewhere on the page, for example on an error-panel or label
LblError.Text = "Duplicates detected: " +
string.Join(",", duplicates.Select(d => d.ToString()));
Of course you could also use a loop to check if all combinations are unqiue.