OracleTransaction Update Gridview via Drop Down List - c#

I am trying to use a drop down list that I have bound to a cell in a GridView to call an SQL UPDATE statement to change a record in the GridView itself. Here is the code below:
<asp:TemplateField HeaderText="Send To...">
<ItemTemplate>
<asp:DropDownList ID="StatusDD" runat="server" AutoPostBack="false" OnSelectedIndexChanged="StatusDD_SelectedIndexChanged">
<asp:ListItem Value="A">Active</asp:ListItem>
<asp:ListItem Value="C">Complete</asp:ListItem>
<asp:ListItem Value="I">In Process</asp:ListItem>
<asp:ListItem Value="E">Error</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
And here is the code behind, this is where my try-catch block hangs my page at ExecuteNonQuery(). Is this the correct syntax of how to do an update? I disabled the AutoPostBack as you can see above but that didn't do anything for me anyway:
protected void StatusDD_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = sender as DropDownList;
ToroGeneral toro = new ToroGeneral();
string connString = toro.GetOracle1ConnectionString();
using (OracleConnection conn1 = new OracleConnection(connString))
{
foreach (GridViewRow row in MMRGrid.Rows)
{
Control ctrl = row.FindControl("StatusDD") as DropDownList;
if (ctrl != null)
{
DropDownList ddl1 = (DropDownList)ctrl;
string qString = "";
// PreQuery work
DropDownList temp = new DropDownList();
temp = (DropDownList)row.FindControl("StatusDD");
string uKey = row.Cells[12].Text;
string tempStr = temp.SelectedValue.ToString().Trim();
if (ddl1.SelectedValue == "A")
{
qString = "UPDATE MATERIALMOVEREQUEST SET PROCESS_FLAG = 'A' WHERE UNIQUEKEY = '" + uKey + "'";
}
else if (ddl1.SelectedValue == "E")
{
qString = "UPDATE MATERIALMOVEREQUEST SET PROCESS_FLAG = 'E' WHERE UNIQUEKEY = '" + uKey + "'";
}
else if (ddl1.SelectedValue == "I")
{
qString = "UPDATE MATERIALMOVEREQUEST SET PROCESS_FLAG = 'I' WHERE UNIQUEKEY = '" + uKey + "'";
}
else if (ddl1.SelectedValue == "C")
{
qString = "UPDATE MATERIALMOVEREQUEST SET PROCESS_FLAG = 'C' WHERE UNIQUEKEY = '" + uKey + "'";
}
else
{
// Error
}
// Change the value of the record in the database.
conn1.Open();
OracleCommand cmd = conn1.CreateCommand();
OracleTransaction myTrans;
cmd.CommandText = qString;
myTrans = conn1.BeginTransaction(IsolationLevel.ReadCommitted);
cmd.Transaction = myTrans;
if (cmd.Connection.State == ConnectionState.Closed)
{
cmd.Connection.Open();
}
try
{
cmd.ExecuteNonQuery();
myTrans.Commit();
}
catch
{
myTrans.Rollback();
}
} // if
} // foreach
}

Why don't you use:
string updateSql = "UPDATE MATERIALMOVEREQUEST SET PROCESS_FLAG = :parameter1 WHEREUNIQUEKEY = :parameter2";"
OracleCommand cmd = new OracleCommand(updateString, conn1);
cmd.BindByName = true;
cmd.Parameters.Add("parameter1", Convert.ToChar(ddl1.SelectedValue);
cmd.Parameters.Add("parameter2", uKey);
myTrans = conn1.BeginTransaction(IsolationLevel.ReadCommitted);
cmd.Transaction = myTrans;
try
{
cmd.ExecuteNonQuery();
myTrans.Commit();
}
catch
{
myTrans.Rollback();
}

Related

Prevent duplicates in datagrid when databound

after some testing I came with this way to handle my datagrid. dgVariedad_CellEditEnding use the function nombreVariedadDisponible(txtBoxTemporal.Text) to check if the new value already exist in List<Variedad> variedades and it works. The problem is that the value wont be inserted in the database but will be added in the datagrid control, I can't find a way to cancel the new row in the control.
private List<Variedad> variedades = new List<Variedad>();
private void bindVariedad()
{
using (MySqlCommand cmd = Conexion.con.CreateCommand())
{
cmd.CommandText = "SELECT NOMBRE FROM DATAFRUT_VARIEDADES WHERE ELIMINADO = 'F';";
Conexion.abrirConexion();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable table = new DataTable("DATAFRUT_VARIEDADES");
da.Fill(table);
table.Columns[0].ColumnName = "Nombre";
dgVariedad.ItemsSource = table.DefaultView;
cmd.CommandText = "SELECT * FROM DATAFRUT_VARIEDADES WHERE ELIMINADO = 'F';";
using (MySqlDataReader dr = cmd.ExecuteReader())
{
variedades.Clear();
while (dr.Read())
{
Variedad var = new Variedad();
var.codigo = Convert.ToInt32(dr[0]);
var.nombre = dr[1].ToString();
var.eliminado = Convert.ToChar(dr[2]);
variedades.Add(var);
}
}
}
}
private void dgVariedad_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
TextBox txtBoxTemporal = e.EditingElement as TextBox;
int indice = e.Row.GetIndex();
if (e.Row.IsNewItem)
{
if (nombreVariedadDisponible(txtBoxTemporal.Text))
{
bool insertExitoso = false;
using (MySqlCommand cmd = Conexion.con.CreateCommand())
{
Conexion.abrirConexion();
cmd.CommandText = "INSERT INTO DATAFRUT_VARIEDADES VALUES (default, '" + txtBoxTemporal.Text + "', 'F');";
try
{
cmd.ExecuteNonQuery();
insertExitoso = true;
}
catch
{
MessageBox.Show("Error");
}
Conexion.cerrarConexion();
}
if (insertExitoso)
{
variedades.Add(Variedad.cargarUltimoInsert(txtBoxTemporal.Text));
}
}
else
{
e.Cancel = true;
}
}
else
{
using (MySqlCommand cmd = Conexion.con.CreateCommand())
{
Conexion.abrirConexion();
DataRowView dataRow = (DataRowView)dgVariedad.SelectedItem;
cmd.CommandText = "UPDATE DATAFRUT_VARIEDADES SET NOMBRE = '" + txtBoxTemporal.Text + "' WHERE CODIGO = " + variedades[dgVariedad.SelectedIndex].codigo + ";";
try
{
cmd.ExecuteNonQuery();
variedades[dgVariedad.SelectedIndex].nombre = txtBoxTemporal.Text;
}
catch(MySqlException mex)
{
MessageBox.Show("Error " + mex.Message);
}
Conexion.cerrarConexion();
}
}
}
My table on mysql has 3 fields:
int codigo (primary key, auto increment)
string Nombre (Unique) char
char Eliminado -> Eliminado (Deleted) with values (F = false and V =
true)
Here is how I check if the value already exist.
private bool nombreVariedadDisponible(string nombreAComparar)
{
//busca el nombre en la lista "variedades"
foreach (Variedad var in variedades)
{
if (var.nombre.ToLower() == nombreAComparar.ToLower() && var.eliminado == 'F')
return false;
}
return true;
}

How to update SQL Table Using DataGridView Values in C#?

enter image description hereI tried to update selected columns of SQL Database table which from DataGridView. But it said my input string is wrong.So how to fix this.(PO_No is the primary key of PO table and it has identity value and also it is the foreign key of PO_Cart table)
public void UpdatePOCartTable(int PO_No,string ISBN_No,int OrderQuantity, decimal UnitPrice, decimal Total)
{
DynamicConnection con = new DynamicConnection();
con.mysqlconnection();
string query = "UPDATE TBL_PO_Cart"
+ " SET ISBN_No = #ISBN_No, OrderQuantity= #OrderQuantity,"
+ "UnitPrice= #UnitPrice, Total=#Total"
+ "WHERE PO_No = #PO_No";
con.sqlquery(query);
con.cmd.Parameters.Add(new SqlParameter("#PO_No", SqlDbType.Int));
con.cmd.Parameters["#PO_No"].Value = PO_No;
con.cmd.Parameters.Add(new SqlParameter("#ISBN_No", SqlDbType.NVarChar));
con.cmd.Parameters["#ISBN_No"].Value = ISBN_No;
con.cmd.Parameters.Add(new SqlParameter("#OrderQuantity", SqlDbType.NVarChar));
con.cmd.Parameters["#OrderQuantity"].Value = OrderQuantity;
con.cmd.Parameters.Add(new SqlParameter("#UnitPrice", SqlDbType.Money));
con.cmd.Parameters["#UnitPrice"].Value = UnitPrice;
con.cmd.Parameters.Add(new SqlParameter("#Total", SqlDbType.Money));
con.cmd.Parameters["#Total"].Value = Total;
con.nonquery();
}
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();
for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
{
PO.UpdatePOCartTable(Convert.ToInt32(txtPONo.Text),dataGridView1.Rows[i].Cells[1].Value.ToString(), Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value.ToString()), Convert.ToDecimal(dataGridView1.Rows[i].Cells[3].Value.ToString()), Convert.ToDecimal(dataGridView1.Rows[i].Cells[4].Value.ToString()));
}
}
else
{
MessageBox.Show("Please Provide Details!");
}
dataGridView1.Rows.Clear();
ClearData();
retviewPO_No();
MessageBox.Show("Record Updated Successfully");
}
catch (Exception ex)
{
MessageBox.Show("Error Occured" + ex.Message);
}
}
When Updating SQL I normally use the following code:
String CommandLine = "UPDATE CA_temp_data SET TimePast=#selectTot WHERE TicketNumber=#id";
using (SqlConnection Conn = new SqlConnection("Data Source=" + hostString + ";User ID=" + usernamestring + ";Password=" + sqlpassword))
{
try
{
SqlCommand cmd = new SqlCommand(CommandLine, Conn);
cmd.Parameters.AddWithValue("#id", ticket);
cmd.Parameters.AddWithValue("#selectTot", time);
using (Conn)
{
Conn.Open();
cmd.ExecuteNonQuery();
Conn.Close();
}
}
catch (System.Exception excep)
{
}

Data won't update (database is SQL Server)

I have a problem in updating my data.
I have Home.aspx.cs and a class HomeClass.cs. I have a gridview in which I want to do my updating but it doesn't work.
It won't return the successful message and I also checked my SQL Server database but there's no changes.
This is my Home.aspx.cs:
protected void DataGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
GridViewRow row = DataGridView.Rows[e.RowIndex];
// get old data
HiddenField hidedescription = row.FindControl("hiddendescription") as HiddenField;
HiddenField hidepkgcode = row.FindControl("hiddenpkgcode") as HiddenField;
HiddenField hideoprcode = row.FindControl("hiddenoprcode") as HiddenField;
// get new data
DropDownList Ed_description = DataGridView.Rows[e.RowIndex].FindControl("Editdescription") as DropDownList;
TextBox Ed_pkgcode = DataGridView.Rows[e.RowIndex].FindControl("Editpkgcode") as TextBox;
TextBox Ed_oprcode = DataGridView.Rows[e.RowIndex].FindControl("Editoprcode") as TextBox;
string Message = obj.Update_Data(Ed_description.SelectedItem,
Ed_pkgcode,
Ed_oprcode,
hidedescription.Value,
hidepkgcode.Value,
hideoprcode.Value);
Fill_Grid();
Literal1.Text = Message;
}
catch (Exception ex)
{
}
}
void Fill_Grid()
{
try
{
DataGridView.DataSource = obj.Get_Data();
DataGridView.DataBind();
}
catch (Exception ex)
{
}
}
And this is my HomeClass.cs class:
static string Connect = WebConfigurationManager.ConnectionStrings["CONSTRING"].ConnectionString;
SqlConnection con = new SqlConnection(Connect);
SqlCommand cmd;
SqlDataAdapter adap;
DataTable dt;
public string Update_Data(ListItem listItem,
TextBox Ed_pkgcode,
TextBox Ed_oprcode,
string hidedescription,
string hidepkgcode,
string hideoprcode)
{
// update data
string getnewType = listItem.Text;
if (getnewType == "Data 1")
{
getnewType = "Y";
}
if (getnewType == "Data 2")
{
getnewType = "N";
}
// old data
if (hidedescription == "Data 1") { hidedescription = "Y"; }
if (hidedescription == "Data 2") { hidedescription = "N"; }
con.Open();
cmd = new SqlCommand("Update PAORStdTime set type='" + getnewType +
"', pkgcode='" + Ed_pkgcode.Text +
"', oprcode='" + Ed_oprcode.Text +
"' where type= '" + hidedescription +
"' and pkgcode ='" + hidepkgcode +
"' and oprcode ='" + hideoprcode + "'" , con);
cmd.ExecuteNonQuery();
con.Close();
return "Updated successfully";
}
where type = hidedescription
and pkgcode = hidepkgcode
and pkgcode = hideoprcode
There is no way that pkgcode will be equal to both hidepkgcode and hideoprcode. I believe the code below is what you want.
where type = hidedescription
and pkgcode = hidepkgcode
and oprcode = hideoprcode

fill dropdownlist from onselectindexchanged

im using asp.net and c#
im using 2 dropdownlist like dd1,dd2
how to fill 2nd dropdownlist dd2 by dd1 onselectindexchanged
my code is,
<asp:DropDownList ID="ddMedType" runat="server" CssClass="drop" AutoPostBack="true" OnSelectedIndexChanged="ddMedType_SelectedIndexChanged">
<asp:ListItem Value="0">-Select-</asp:ListItem>
<asp:ListItem Value="Tablet">Tablet</asp:ListItem>
<asp:ListItem Value="Tonic">Tonic</asp:ListItem>
<asp:ListItem Value="Capsules">Capsules</asp:ListItem>
<asp:ListItem Value="DispoTab">Disposable Tablet</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddMedName" runat="server" CssClass="drop" >
<asp:ListItem Value="0">-Select-</asp:ListItem>
</asp:DropDownList>
protected void ddMedType_SelectedIndexChanged(object sender, EventArgs e)
{
string MedType = ddMedType.SelectedItem.Text;
string str = "select MedicineName,MedicineId from MedicineMaster where MedicineType = '" + MedType + "'";
cmd = new SqlCommand(str, con);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
ddMedName.SelectedValue= reader["MedicineId"].ToString();
}
}
here the condition returns 2 items, but dropdownlist dd2 returns only 1 ...
You are setting the SelectedValue, this does not mean you're adding or removing items in your dropdownlist
DataTable medicines= new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("select MedicineName,MedicineId from MedicineMaster where MedicineType = '" + MedType + "'", con);
adapter.Fill(subjects);
ddMedName.DataSource = subjects;
ddMedName.DataTextField = "MedicineName";
ddMedName.DataValueField = "MedicineId";
ddMedName.DataBind();
}
catch (Exception ex)
{
// Handle the error
}
}
// Add the initial item - you can add this even if the options from the
// db were not successfully loaded
ddMedName.Items.Insert(0, new ListItem("-Select-", "0"));
You can also do it with the reader as follows:
ddMedName.Items.Clear();
ddMedName.Items.Add(new ListItem("-Select-", "0"));
while (reader.Read())
{
ddMedName.Items.Add(new ListItem(reader["MedicineName"].ToString(), reader["MedicineId"].ToString());
}
Try add item in the DropdownList..
DropDownList1.Items.Add(new ListItem(reader["MedicineId"].ToString(), reader["MedicineId"].ToString()));
Here is one solution may help you:
protected void ddMedType_SelectedIndexChanged(object sender, EventArgs e)
{
string MedType = ddMedType.SelectedItem.Text;
string str = "select MedicineName,MedicineId from MedicineMaster where MedicineType = '" + MedType + "'";
cmd = new SqlCommand(str, con);
SqlDataReader reader = cmd.ExecuteReader();
ddMedName.DataSource = reader;
ddMedName.DataTextField = "MedicineName";
ddMedName.DataValueField = "MedicineId";
ddMedName.DataBind();
}

AutoCompleteExtender AJAX Question

Ok I am using the code below in file called autocomplete.asmx (web service file) my main question is do I need to create a different web service for every field I want my auto complete to work for? IE maybe I would like to have the Company Name pulled out instead of country, but another time maybe name, now I know this just involves changing the select statement but How could I go about doing this so that depending on what field it is, it knows what select statement to use?
Thanks
public class AutoComplete : System.Web.Services.WebService
{
[WebMethod]
public string[] GetCountriesList(string prefixText)
{
DataSet dtst = new DataSet();
SqlConnection sqlCon = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
string strSql = "SELECT CountryName FROM Tbl_ooo WHERE CountryName LIKE '" + prefixText + "%' ";
SqlCommand sqlComd = new SqlCommand(strSql, sqlCon);
sqlCon.Open();
SqlDataAdapter sqlAdpt = new SqlDataAdapter();
sqlAdpt.SelectCommand = sqlComd;
sqlAdpt.Fill(dtst);
string[] cntName = new string[dtst.Tables[0].Rows.Count];
int i = 0;
try
{
foreach (DataRow rdr in dtst.Tables[0].Rows)
{
cntName.SetValue(rdr["CountryName"].ToString(), i);
i++;
}
}
catch { }
finally
{
sqlCon.Close();
}
return cntName;
}
}
Yes, you can use same webservice webmethod to populate country and company.
For that you want to use ContextKey property in ajax AutoCompleteExtender control
Below is the sample Code
Markup :
Search
<asp:TextBox ID="txtSearch" CssClass="textBlackBold" runat="server" Width="350px"></asp:TextBox>
<asp:DropDownList ID="ddlType" runat="server" AutoPostBack="True" onselectedindexchanged="ddlType_SelectedIndexChanged">
<asp:ListItem Value="0">Country</asp:ListItem>
<asp:ListItem Value="1">Companies</asp:ListItem>
</asp:DropDownList>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
CompletionListCssClass="autocomplete_completionListElement"
CompletionListItemCssClass="autocomplete_listItem"
CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
EnableCaching="true" ContextKey="Products" UseContextKey="true"
TargetControlID="txtSearch" MinimumPrefixLength="1"
ServiceMethod="GetInfo" ServicePath="~/WebService.asmx" >
</asp:AutoCompleteExtender>
Code Behind C# Code :
protected void ddlType_SelectedIndexChanged(object sender, EventArgs e)
{
string strContextKey = "";
if(ddlType.SelectedValue.ToString() == "0")
strContextKey = "Country";
else
strContextKey = "Companies";
AutoCompleteExtender1.ContextKey = ddlType.SelectedItem.Text;
}
WebService Code :
[WebMethod]
public string[] GetInfo(string prefixText, string contextKey)
{
DataSet dtst = new DataSet();
SqlConnection sqlCon = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
string strSql = "";
if (contextKey == "Country")
{
strSql = "SELECT CountryName FROM Tbl_ooo WHERE CountryName LIKE '" + prefixText + "%' ";
}
else if(contextKey == "Companies")
{
strSql = //Other SQL Query
}
SqlCommand sqlComd = new SqlCommand(strSql, sqlCon);
sqlCon.Open();
SqlDataAdapter sqlAdpt = new SqlDataAdapter();
sqlAdpt.SelectCommand = sqlComd;
sqlAdpt.Fill(dtst);
string[] cntName = new string[dtst.Tables[0].Rows.Count];
int i = 0;
try
{
foreach (DataRow rdr in dtst.Tables[0].Rows)
{
cntName.SetValue(rdr[0].ToString(),i);
i++;
}
}
catch { }
finally
{
sqlCon.Close();
}
return cntName;
}

Categories

Resources