Suppose if I have 4 rows in the gridview and I want to delete only second row so how to get the dynamic ID from the table so that I can delete that particular row with unique ID
Here is my query, but I am not able to bring the respective ID:-
protected void GrdTraining_DeleteCommand(object sender, Obout.Grid.GridRecordEventArgs e)
{
if (Session["dt10"] != null)
{
dt10 = (DataTable)Session["dt10"];
}
else
{
BindDatatable();
}
DataRow[] grdTrain = dt10.Select("SR_NO=" + Convert.ToString(e.Record["SR_NO"]));
dt10.Rows.Remove(grdTrain[0]);
AddToViewState("GrdTraining");
CF.ExecuteDT("DELETE FROM EMP_ATTACHED_DOCUMENTS where mkey="+ ); // mkey is my unique column in the table, how to get the ID here for the row which I want to delete ??
}
Please suggest
After so much of discussion with Quan Nguyen. And with my team. Finally I got the solution which worked for me.
The logic was simple but was confused with the relation of the SQL Query
Here is the code:-
protected void GrdTraining_DeleteCommand(object sender, Obout.Grid.GridRecordEventArgs e)
{
if (Session["dt10"] != null)
{
dt10 = (DataTable)Session["dt10"];
}
else
{
BindDatatable();
}
DataRow[] grdTrain = dt10.Select("SR_NO=" + Convert.ToString(e.Record["SR_NO"]));
dt10.Rows.Remove(grdTrain[0]);
AddToViewState("GrdTraining");
string strempcode = CF.ExecuteScaler("select emp_card_no from emp_mst a, user_mst b where a.mkey=b.employee_mkey and b.mkey=" + Session["UserId"]);
CF.ExecuteDT("DELETE FROM EMP_ATTACHED_DOCUMENTS where category_id = 'TC' and pk1_value='" + strempcode + "' and document_id='" + e.Record["SR_NO"] + "'");
}
Related
I'm putting together a project that has a form to fill out which then populates a query from a separate data table. It will always only grab one row based on the inputs, which is then used for a price calculation. I have two places in the code using the same setup. The first one uses a single combo box for the query and it works great, but the second part uses two combo boxes to make an "AND" query and I can't figure out why it isn't working, it doesn't seem to recognize the selections and place them into the calculation. Below is the code for that part, any help would be appreciated!
private void plant_AmountTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
try
{
plantamountResult = Convert.ToDecimal(plant_AmountTextBox.Text);
}
catch (Exception)
{
MessageBox.Show("Please enter a valid amount");
}
try
{
DataRowView rowviewpml = material_NameComboBox.SelectedItem as DataRowView;
materialNameSelection = "";
if (rowviewpml != null)
{
materialNameSelection = rowviewpml.Row["Material_Species"] as string;
}
DataRowView rowviewst = stockComboBox.SelectedItem as DataRowView;
stockSelection = "";
if (rowviewst != null)
{
stockSelection = rowviewst.Row["Stock_Type"] as string;
}
string mcSearch = "Material_Species = '" + materialNameSelection + "' AND Stock_Type = '" + stockSelection + "'";
Plant_Material_PricingTableAdapter pmpTA = new Plant_Material_PricingTableAdapter();
DataTable pmpDT = pmpTA.GetData();
DataRow[] pmpRow = pmpDT.Select(mcSearch);
foreach(DataRow row in pmpRow)
{
materialEstCost = Convert.ToDouble(pmpRow[0]["Previous_FY_Quotes"]);
}
plantestCostCalc.Text = "$" + ((decimal)materialEstCost * plantamountResult).ToString();
}
catch
{
plantestCostCalc.Text = "0";
}
}
I would like to know when I load data to datagridview to update them, after add new rows to existing rows,how can I update newly added rows without duplication of existing rows. Here my code
private void btnedit_Click(object sender, EventArgs e)
{
DynamicConnection con = new DynamicConnection();
try
{
if (txtPONo.Text != "" || cmbsupID.Text != "" || date1.Text != "" || requireddate.Text != "" || txtgrandTotal.Text != "")
{
PurchaseOrder PO = new PurchaseOrder();
if (cmbsupID.Text.Contains('-'))
{
string str = cmbsupID.Text;
int index = str.IndexOf('-');
if (index > 0)
{
int value = int.Parse(str.Substring(0, index));
PO.UpdatePurchseOrderTable(Convert.ToInt32(txtPONo.Text), value, date1.Text, requireddate.Text, Convert.ToDouble(txtgrandTotal.Text));
}
}
else
{
int value2 = Convert.ToInt32(cmbsupID.Text);
PO.UpdatePurchseOrderTable(Convert.ToInt32(txtPONo.Text), value2, date1.Text, requireddate.Text, Convert.ToDouble(txtgrandTotal.Text));
}
for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
{
int PONO = Convert.ToInt32(txtPONo.Text);
string column1 = Convert.ToString(dataGridView1.Rows[i].Cells[1].Value);
int column2 = Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value);
double column3= Convert.ToDouble(dataGridView1.Rows[i].Cells[3].Value);
double column4 = Convert.ToDouble(dataGridView1.Rows[i].Cells[4].Value);
PO.UpdatePOCartTable(PONO,column1,column2,column3,column4);
}
}
else
{
MessageBox.Show("Please Provide Details!");
}
dataGridView1.Rows.Clear();
ClearData();
retviewPO_No();
MessageBox.Show("Record Updated Successfully");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
additional-
In my program which has datagridview for insert,update or delete Purchase Order and it behave like as a shopping cart.This datagridview consist of BookName,ISBNNo,Order quantity,unit price and total.When I insert this datagridview data to database,each row insert with unique id PO_Cart_No(pk) which has identity value.
And also other background textbox details which are Po_No,supplier_Id and Grand total details insert into separate table which called PO table.And also this two tables link with foreign key PO_No.My question is when I add new row to existing row to update database,that new row didn't insert and only other row data has updated.
I want to populate hierarchical Tree Structure using recursive data from the database using button_click event
I have the following record in the table.
bomItem partId
500101 100200
500101 500100
500101 100280
500100 320255
I want to show Tree as shown below
500101
+----100200
+----500100
+----300255
+----100280
// Note: bomItem is the parent and partId is the child fields
The problem i am having:
when navigate to the next record keeps tree structure from the previous record, i want to clear Tree-view when i navigate to another record.
To show the full tree structure i have to populate the child's first
Here is the code i used
//button click event
private void button4_Click(object sender, EventArgs e)
{
_command = new SqlCommand("SELECT * FROM [BOMDETAIL] where bomItem= '" + int.Parse(bomItemTextBox.Text) + "' and bomRev= '" + bomRevComboBox.Text + "'", _connection);
_adapter = new SqlDataAdapter(_command);
_adapter.Fill(objdataset);
_connection.Close();
try
{
TreeNode node = new TreeNode(bomItemTextBox.Text);
filltree(node, int.Parse(bomItemTextBox.Text), objdataset);
treeView2.Nodes.Add(node);
//dataGridView1.DataSource = objdataset.Tables[0];
}
catch (Exception c)
{
MessageBox.Show(c.ToString());
}
}
//filetree()
private void filltree(TreeNode parentnode, int parentid, DataSet dataset)
{
// Fill Tree Function to poplulate treeeview control
String str = null;
try
{
foreach (DataRow row in dataset.Tables[0].Rows)
{
if (Convert.ToInt32(row["bomItem"]) == parentid)
{
str = row["partId"].ToString();
TreeNode new_parent_node = parentnode.Nodes.Add(str);
int parent_id = Convert.ToInt32(row["partId"]);
filltree(new_parent_node, parent_id, dataset);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Image describing problem No 1
is it possible to create a value range constraint on a DataTable in C#?
I'm dynamically adding a column to a DataTable:
this.PrimaryCorrelationMatrix.Columns.Add(sName, typeof(int));
but I'd like all values within this Column to be integers from [0, 10]. Can I implement such a constraint directly on the DataTable?
The next best option I can think of is to create some object with possible values [0, 10], and instead of typeof(int), using typeof(specialObj).
One way to do this is to inspect the e.ProposedValue in the ColumnChanging event of the DataTable.
To have the constraint on a particular column, you can use the ExtendedProperties collection of the DataColumn to act as your flag to check those constraints:
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("Range", typeof(int));
dc.ExtendedProperties.Add("Min", 0);
dc.ExtendedProperties.Add("Max", 10);
dt.Columns.Add(dc);
dt.ColumnChanging += dt_ColumnChanging;
In the ColumnChanging event, you would check if those properties exist, then use them:
void dt_ColumnChanging(object sender, DataColumnChangeEventArgs e) {
if (e.Column.ExtendedProperties.ContainsKey("Min") &&
e.Column.ExtendedProperties.ContainsKey("Max")) {
int min = (int)e.Column.ExtendedProperties["Min"];
int max = (int)e.Column.ExtendedProperties["Max"];
if ((int)e.ProposedValue < min) e.ProposedValue = min;
if ((int)e.ProposedValue > max) e.ProposedValue = max;
}
}
I can recommend you to forget about data tables and use classes. You can use data annotation to validate your model.
Use this attribute to validate a range of values for an specific property/
This code is extracted from the specified article(example of class making the validation of a range):
public class Product
{
[Range(5, 50)]
public int ReorderLevel { get; set; }
[Range(typeof(Decimal),"5", "5000")]
public decimal ListPrice { get; set; }
}
Your are going to find a lot of benefits of using classes.
This is an old post but I am using a solution to sync the Check_Constraints NOT filled by the OleDbDataAdapter.FillSchema on Access Databases worth to mention. Just used a OleDbConnection to retrieve GetOleDbSchemaTable and foreach() the rows extracting the validation text expression and created an anonymous delegate at the appropriate Table & Column attached to the proper Table.ColumnChanging event. The string validation provided by the Access schema will then be evaluated dynamically by the handy Eval() function described here. There is my code:
DataTable schemaTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Check_Constraints, null);
// Attach delegate Eval() of each Check_Constraints on proper Table/Column
foreach (DataRow myField in schemaTable.Rows)
{
string constraint_name = "";
string check_clause = "";
foreach (DataColumn myProperty in schemaTable.Columns)
{
if (myProperty.ColumnName == "CONSTRAINT_NAME")
constraint_name = myField[myProperty.ColumnName].ToString();
if (myProperty.ColumnName == "CHECK_CLAUSE")
check_clause = myField[myProperty.ColumnName].ToString();
}
var rule = constraint_name.Replace("[", "").Replace("]", "").Split('.');
if (rule.Length == 3 && dataset.Tables.Contains(rule[0]) && dataset.Tables[rule[0]].Columns.Contains(rule[1]) && String.IsNullOrEmpty(check_clause) == false)
{
dataset.Tables[rule[0]].ColumnChanging += delegate (object sender, DataColumnChangeEventArgs e)
{
if (e.Column.ColumnName == rule[1] && Convert.ToBoolean(ToolBox.Eval(e.ProposedValue + check_clause)) == false)
{
throw new Exception("Tabela: " + rule[0] + ", coluna: " + rule[0] + ", cheque: " + check_clause);
}
};
Debug.WriteLine(rule[0] + "." + rule[1] + ": " + check_clause);
}
}
MS DynamicData's Children.ascx.cs file has a Page_Load method that returns a hyperlink which says "View Children". I want to append the number of children to the end of the hyperlink text. Below is my attempt. How can I make the hyperlink say "View Children - # entries" ?
protected void Page_Load(object sender, EventArgs e)
{
HyperLink1.Text = "View " + ChildrenColumn.ChildTable.DisplayName;
//The following code gives the total entries.
//How do I get the number of children only?
//int entries = 0;
//foreach (var entry in ChildrenColumn.ChildTable.GetQuery()) { entries++; }
//string entryText = (entries == 1) ? "entry" : "entries";
//HyperLink1.Text= HyperLink1.Text + " " + entries + " " + entryText;
}
Actually it is not that hard. You can add the following Method to your Children.ascx.cs file:
protected override void OnDataBinding(EventArgs e)
{
base.OnDataBinding(e);
object entity;
ICustomTypeDescriptor rowDescriptor = Row as ICustomTypeDescriptor;
if (rowDescriptor != null)
{
// Get the real entity from the wrapper
entity = rowDescriptor.GetPropertyOwner(null);
}
else
{
entity = Row;
}
// Get the collection and make sure it's loaded
RelatedEnd entityCollection = Column.EntityTypeProperty.GetValue(entity, null) as RelatedEnd;
if (entityCollection == null)
{
throw new InvalidOperationException(String.Format("The Children template does not support the collection type of the '{0}' column on the '{1}' table.", Column.Name, Table.Name));
}
if (!entityCollection.IsLoaded)
{
entityCollection.Load();
}
int count = 0;
var enumerator = entityCollection.GetEnumerator();
while (enumerator.MoveNext())
count++;
HyperLink1.Text += " (" + count + ")";
}
well, HyperLink1.Text ="SomeString" should make your hyperlink's text be "SomeString"
HyperLink1.Text = "View Children -"+numEntries+" entries";
should make the hyperlink say what you want it to say, so long as numEntries is the right number at the time, at least it works that way on my machine ..
What is the current result of your attempt?
I have found a potential solution here 'FieldTemplates: Children.ascx: Displaying Count' : http://forums.asp.net/t/1466373.aspx/1
I have a very simple generic solution using dynamic:
Override the OnDataBiding method in the Childrex.aspx.cs and use the following code to get the number of child entities.
// get the field using dynamic
dynamic dynamicField = FieldValue;
// get the count property (this is a valid property for an EnitySet)
int count = dynamicField.Count;