Below 2 links give the preview of my sample application.
http://img812.imageshack.us/i/image1adl.jpg/ : shows mine sample application. All fields are self explanatory (if query, let me know)
http://img834.imageshack.us/i/image2vc.jpg/ : shows, when clicked the "Edit" button from the grid, the timings are shown correctly but the order gets disturbed. (See 7:00 coming on the top and then the timings list are seen).
My Questions
How to correct the timings problem? (Link # 2)
Code for "Edit" is below
protected void lnkEdit_Click(object sender, EventArgs e)
{
int imageid = Convert.ToInt16((sender as Button).CommandArgument);
DataSet ds = new DataSet();
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["TestConn"].ConnectionString;
string sql = #"SELECT * FROM Images WHERE IsDeleted=0 and Imageid='"+ imageid +"'";
SqlCommand sqlcommand = new SqlCommand(sql, sqlconn);
sqlcommand.CommandType = CommandType.Text;
sqlcommand.CommandText = sql;
SqlDataAdapter da = new SqlDataAdapter(sqlcommand);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
txtImageName.Text = ds.Tables[0].Rows[0].ItemArray[1].ToString();
chkIsActive.Checked = Convert.ToBoolean(ds.Tables[0].Rows[0]["IsActive"].ToString());
ddlStartTime.DataSource = ds;
ddlStartTime.DataTextField = ds.Tables[0].Columns["StartTime"].ColumnName.ToString();
ddlStartTime.DataValueField = ds.Tables[0].Columns["ImageId"].ColumnName.ToString();
ddlStartTime.DataBind();
ddlEndTime.DataSource = ds;
ddlEndTime.DataTextField = ds.Tables[0].Columns["EndTime"].ColumnName.ToString();
ddlEndTime.DataValueField = ds.Tables[0].Columns["ImageId"].ColumnName.ToString();
ddlEndTime.DataBind();
BindDropDownList();
IsEdit = true;
}
When i edit the existing record in the grid, i am getting the values, but the record is not being updated but added as a new record into db. I am aware that i am suppose to write update script. But where to write that?
Below the code is for the same;
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
try
{
string strImageName = txtImageName.Text.ToString();
int IsActive = 1;
if (chkIsActive.Checked)
IsActive = 1;
else
IsActive = 0;
string startDate = ddlStartTime.SelectedItem.Text;
string endDate = ddlEndTime.SelectedItem.Text;
if ( Convert.ToDateTime(endDate) - Convert.ToDateTime(startDate) > new TimeSpan(2, 0, 0) || Convert.ToDateTime(endDate)- Convert.ToDateTime(startDate) < new TimeSpan(2,0,0))
{
//Response.Write(#"<script language='javascript'> alert('Difference between Start Time and End Time is 2 hours'); </script> ");
lblHours.Visible = true;
lblHours.Text = "Difference between Start Time and End Time should be 2 hours";
return;
}
if (checkConflictTime())
{
lblMessage.Visible = true;
lblMessage.Text = "Time Conflict";
return;
}
//if (checkTimeBetween())
//{
//}
if (fuFileUpload.PostedFile != null && fuFileUpload.PostedFile.FileName != "")
{
lblHours.Visible = false;
byte[] imageSize = new Byte[fuFileUpload.PostedFile.ContentLength];
HttpPostedFile uploadedImage = fuFileUpload.PostedFile;
uploadedImage.InputStream.Read(imageSize, 0, (int)fuFileUpload.PostedFile.ContentLength);
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["TestConn"].ConnectionString;
SqlCommand cmd = new SqlCommand();
if (IsEdit == false)
{
cmd.CommandText = "Insert into Images(FileName,FileContent,IsDeleted,IsActive,StartTime,EndTime) values (#img_name, #img_content,#IsDeleted,#IsActive,#StartTime,#EndTime)";
}
else
{
cmd.CommandText = "Update Images set FileName=#img_name, FileContent=#img_content, IsDeleted= #IsDeleted,IsActive= #IsActive, StartTime=#StartTime,EndTime=#EndTime";
}
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlconn;
SqlParameter ImageName = new SqlParameter("#img_name", SqlDbType.NVarChar, 50);
ImageName.Value = strImageName.ToString();
cmd.Parameters.Add(ImageName);
SqlParameter ActualImage = new SqlParameter("#img_content", SqlDbType.VarBinary);
ActualImage.Value = imageSize;
cmd.Parameters.Add(ActualImage);
SqlParameter DeletedImage = new SqlParameter("#IsDeleted", SqlDbType.Bit);
DeletedImage.Value = 0;
cmd.Parameters.Add(DeletedImage);
SqlParameter IsActiveCheck = new SqlParameter("#IsActive", SqlDbType.Bit);
IsActiveCheck.Value = IsActive;
cmd.Parameters.Add(IsActiveCheck);
SqlParameter StartDate = new SqlParameter("#StartTime", SqlDbType.NVarChar, 100);
StartDate.Value = startDate;
cmd.Parameters.Add(StartDate);
SqlParameter EndDate = new SqlParameter("#EndTime", SqlDbType.NVarChar, 100);
EndDate.Value = endDate;
cmd.Parameters.Add(EndDate);
sqlconn.Open();
int result = cmd.ExecuteNonQuery();
sqlconn.Close();
if (result > 0)
{
lblMessage.Visible = true;
lblMessage.Text = "File Uploaded!";
gvImages.DataBind();
}
}
}
catch (Exception ex)
{
lblMessage.Text = ex.ToString();
}
}
}
Please help!
Where do you define Bool/Bolean IsEdit? I think its value is reset on page postback, that's why it is always false and the record is being inserted. I would suggest you to use a hidden field to track this and set its value there and check the value upon insert/updating. Finally it will be something like...
if (ds.Tables[0].Rows.Count > 0)
{
//your code
hiddenField.Value = "true"; // you can set default value to false
}
and then after
if (hiddenField.Value == "false")
{
cmd.CommandText = "Insert into Images(FileName,FileContent,IsDeleted,IsActive,StartTime,EndTime) values (#img_name, #img_content,#IsDeleted,#IsActive,#StartTime,#EndTime)";
}
else
{
cmd.CommandText = "Update Images set FileName=#img_name, FileContent=#img_content, IsDeleted= #IsDeleted,IsActive= #IsActive, StartTime=#StartTime,EndTime=#EndTime";
}
Related
I have table called TBL_PRODUCTS
CREATE TABLE TBL_PRODUCTS
(
Products_ID varchar(50) PRIMARY KEY,
Products_Name varchar(100) NOT NULL,
Products_Categorys_ID int,
Products_Qty DECIMAL(16,0),
Products_Sales_Price DECIMAL(16,0),
Products_Cost_Price DECIMAL(16,0)
);
and I have a datagridview on my windows application which has 6 columns:
(Products_ID, Products_Name, Products_Categorys_Name, Products_Qty, Products_Sales_Price, Products_Total)
I want the user when he write on the 1st column (Products_ID) the code of the product it show on the same row the other details on that row like (Products_Name, Products_Categorys_Name, Products_Sales_Price) and so on ...
How I can make something like that?
I have tried this code:
SqlConnection con = new SqlConnection("Data Source=GMCADIOM-PC;Initial Catalog=TEMP;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
string sqlqry = "SELECT [Products_ID] as 'كود المنتج',[Products_Name] as 'اسم المنتج',Products_Categorys_Name as 'اسم الصنف',[Products_Qty] as 'الكميه المتاحه',[Products_Sales_Price] as 'سعر البيع',[Products_Cost_Price] as 'سعر الشراء' FROM TBL_PRODUCTS INNER JOIN TBL_PRODUCTS_CATEGORYS ON TBL_PRODUCTS_CATEGORYS.Products_Categorys_ID=TBL_PRODUCTS.Products_Categorys_ID WHERE [Products_ID] LIKE '"+ dgvBillsList.CurrentRow.Cells[0].Value.ToString()+ "'";
SqlCommand cmd = new SqlCommand(sqlqry, con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
try
{
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
dgvBillsList.CurrentRow.Cells["Products_ID"].Value = dt.Rows[i]["كود المنتج"];
dgvBillsList.CurrentRow.Cells["Products_Name"].Value = dt.Rows[i]["اسم المنتج"];
dgvBillsList.CurrentRow.Cells["Products_Categorys_Name"].Value = dt.Rows[i]["اسم الصنف"];
dgvBillsList.CurrentRow.Cells["Products_Sales_Price"].Value = dt.Rows[i]["سعر البيع"];
}
}
else
{
var result = MessageBox.Show("هذا المنتج غير موجود بقاعده البيانات ، هل تريد اضافته ؟؟", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
frmProductsNew frm = new frmProductsNew();
frm.StartPosition = FormStartPosition.CenterScreen;
frm.ShowDialog();
}
else if (result == DialogResult.No)
{
//dgvBillsList.CurrentRow.Cells[0].Value = null;
//dgvBillsList.CurrentRow.Cells[0].Selected = true;
//dgvBillsList.CurrentCell = dgvBillsList.CurrentRow.Cells[0];
//dgvBillsList.CurrentCell.Selected = true;
//dgvBillsList.BeginEdit(true);
//dgvBillsList.CurrentCell = dgvBillsList.Rows[dgvBillsList.Rows.Count].Cells[0];
}
}
CONF_Calculate.Calculate_DGV_Products(dgvBillsList);
CONF_Calculate.Calculate_DGV_Total(dgvBillsList, txtBillsAmount);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
but it gives me errors on the query side
Object reference not set to an instance of an object on
dgvBillsList.CurrentRow.Cells[0].Value.ToString()
Thanks for the help in advance.
Im trying to use update query in C#
Error : command is getting executed even if I use incorrect values
Design view
Code :
protected void Button1_Click(object sender, EventArgs e)
{
try
{
con.Open();
cmd = new SqlCommand("update Comcast_AvayaID set Status='Inactive' where Employee_Id='" + TxtEMPID.Text + "' and AvayaID ='" + TxtAvayaID.Text + "'", con);
cmd = new SqlCommand("UPDATE Avaya_Id SET Status = 'UnAssigned' where Avaya_ID ='" + TxtAvayaID.Text + "'", con);
cmd.ExecuteNonQuery();
LBLSuccess.Visible = true;
LBLSuccess.Text = "Deactivation Successfull";
con.Close();
}
catch (SqlException ex)
{
LBLSuccess.Visible = true;
LBLSuccess.Text = "Deactivation Unsuccessfull";
}
your code would look better like this, it not the most optimal, but ia already a way better piece of code then your snippet
1) added parameters using a helper function for the sql injection issue
2) an ExecuteNonQuery returns the rows affected, so if you are expecting that 1 row was updated, you can check on that
3) if you update a row with an id that not exists, it will not throw a SqlException like you are expecting in your code, this happens e.g. when locking occurs
public void Update()
{
var con = new SqlConnection();
try
{
var empId = TxtEMPID.Text
var avayaId = TxtAvayaID.Text
con.Open();
var cmd1 = new SqlCommand("update Comcast_AvayaID set Status='Inactive' where Employee_Id=#empId and AvayaID = #avayaId", con);
cmd1.Parameters.Add(AddParameter("#empId",empId));
cmd1.Parameters.Add(AddParameter("#avayaId", avayaId));
var cmd2 = new SqlCommand("UPDATE Avaya_Id SET Status = 'UnAssigned' where Avaya_ID =avayaId", con);
cmd2.Parameters.Add(AddParameter("#avayaId", avayaId));
var rowsaffected1 = cmd1.ExecuteNonQuery();
var rowsAffected2 = cmd2.ExecuteNonQuery();
if (rowsaffected1 == 1 && rowsAffected2 == 1)
{
//success code goes here
//--------
LBLSuccess.Visible = true;
LBLSuccess.Text = "Deactivation Successfull";
}
else
{
// failure code goes here
//-----------------------
LBLSuccess.Visible = true;
LBLSuccess.Text = "Deactivation Unsuccessfull";
}
}
catch (SqlException ex)
{
//handle errors
}
finally
{
con.Close();
}
Console.ReadLine();
}
private SqlParameter AddParameter(string name, object value) {
var par = new SqlParameter();
par.ParameterName = name;
par.Value = value;
return par;
}
If you put "incorrect" values it just updates zero of records. No errors/exception expected here.
Hi Guys I am trying to understand how to save and edited row to the database
private void BudgetGrid_RowEditEnding(object sender,
DataGridRowEditEndingEventArgs e)
{
SqlCommand gridcmd = new SqlCommand();
SqlConnection rwConn = null;
rwConn = new SqlConnection("server=localhost;" +
"Trusted_Connection=yes;" + "database=Production; " + "connection
timeout=30");
gridcmd.Connection = rwConn;
rwConn.Open();
//gridcmd.CommandText =
//"SELECT Id, Name, Quantity, Rate, Time FROM Budget";
gridcmd.CommandText =
"UPDATE Budget SET Id = #id, Name = #Name, " +
"Quantity = #Qty, Rate = #Rte WHERE Time = #Time";
SqlDataAdapter gridda = new SqlDataAdapter(gridcmd);
string strId = "#id".ToString();
int intID;
bool bintID = Int32.TryParse(strId, out intID);
string strName = "#Name".ToString();
string strQty = "#Qty".ToString();
int intQty;
bool bintQty = Int32.TryParse(strQty, out intQty);
string strRte = "#Rte".ToString();
int intRte;
bool bintRte = Int32.TryParse(strRte, out intRte);
string strTime = "#Time".ToString();
gridda.SelectCommand.Parameters.Add(
new SqlParameter("#id", SqlDbType.Int));
gridda.SelectCommand.Parameters["#id"].SqlValue = intID;
gridda.SelectCommand.Parameters.Add(
new SqlParameter("#Name", SqlDbType.VarChar));
gridda.SelectCommand.Parameters["#Name"].SqlValue = strName;
gridda.SelectCommand.Parameters.Add(
new SqlParameter("#Qty", SqlDbType.Int));
gridda.SelectCommand.Parameters["#Qty"].SqlValue = strQty;
gridda.SelectCommand.Parameters.Add(
new SqlParameter("#Rte", SqlDbType.Int));
gridda.SelectCommand.Parameters["#Rte"].SqlValue = strRte;
gridda.SelectCommand.Parameters.Add(
new SqlParameter("#Time", SqlDbType.VarChar));
gridda.SelectCommand.Parameters["#Time"].SqlValue = strTime;
DataTable griddt = new DataTable("Budget");
gridda.Fill(griddt);
gridda.UpdateCommand =
new SqlCommandBuilder(gridda).GetUpdateCommand();
BudgetGrid.ItemsSource = griddt.DefaultView;
gridda.Update(griddt);
rwConn.Close();
}
it displays fine. I can edit its but when I click on the other tab it does not update it goes back to the original data.
Most of the code I have been going through its either out dated.. or not what I am looking for.
so here is the database
and here is the app
so basically if i hit tab to the next row. under the event BudgetGrid_RowEditEnding it should update the database.. but now its not.
Just copy below codes. I've created all the thing of you and tested successfully. Rather than the first way, I tried to let you go more popular way. Therefore, it took me time to adopt..
Hope this helps you !
SqlDataAdapter da;
DataTable dt;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
SqlConnection Conn = new SqlConnection();
Conn.ConnectionString = yourConnectionString;
Conn.Open();
SqlCommand gridcomm = new SqlCommand();
gridcomm.Connection = Conn;
gridcomm.CommandText = "SELECT Id, Name, Quantity, Rate, Time FROM Budget";
da = new SqlDataAdapter(gridcomm);
SqlDataReader gridreader = gridcomm.ExecuteReader();
while (gridreader.Read())
{
}
gridreader.Close();
dt= new DataTable("Budget");
da.Fill(dt);
dataGrid_Budget.ItemsSource = dt.DefaultView;
Conn.Close();
}
private void dataGrid_Budget_RowEditEnding(object sender, System.Windows.Controls.DataGridRowEditEndingEventArgs e)
{
DataGridRow editedrow = e.Row;
int row_index = (DataGrid)sender).ItemContainerGenerator.IndexFromContainer(editedrow);
for (int k=0;k< 5;k++)
{
DataGridCell cell = GetCell(row_index, k);
TextBlock tb = cell.Content as TextBlock;
if (k==1)
{
dt.Rows[row_index][k] = tb.Text;
}
else if (k == 4)
{
if (tb.Text != "")
{
dt.Rows[row_index][k] = Convert.ToDateTime(tb.Text);
}
}
else
{
dt.Rows[row_index][k] = Convert.ToInt32(tb.Text);
}
}
da.UpdateCommand = new SqlCommandBuilder(da).GetUpdateCommand();
da.Update(dt);
}
public DataGridCell GetCell(int row, int column)
{
DataGridRow rowContainer = GetRow(row);
if (rowContainer != null)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
if (cell == null)
{
dataGrid_Budget.ScrollIntoView(rowContainer, dataGrid_Budget.Columns[column]);
cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
}
return cell;
}
return null;
}
public DataGridRow GetRow(int index)
{
DataGridRow row = (DataGridRow)dataGrid_Budget.ItemContainerGenerator.ContainerFromIndex(index);
if (row == null)
{
dataGrid_Budget.UpdateLayout();
dataGrid_Budget.ScrollIntoView(dataGrid_Budget.Items[index]);
row = (DataGridRow)dataGrid_Budget.ItemContainerGenerator.ContainerFromIndex(index);
}
return row;
}
public static T GetVisualChild<T>(Visual parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChild<T>(v);
}
if (child != null)
{
break;
}
}
return child;
}
Your SQL syntax has to be corrected like,
SqlCommand update_comm = new SqlCommand();
update_comm.Connection = Conn;
update_comm.CommandText = "UPDATE Budget SET id= #u_id, Name= #u_name WHERE person= #psn";
var update_da = new SqlDataAdapter(update_comm);
update_da.SelectCommand.Parameters.Add(new SqlParameter("#u_id", SqlDbType.Int));
update_da.SelectCommand.Parameters["#u_id"].Value = yourintvalue;
update_da.SelectCommand.Parameters.Add(new SqlParameter("#u_name", SqlDbType.NVarChar));
update_da.SelectCommand.Parameters["#u_name"].Value = yourstringvalue;
update_da.SelectCommand.Parameters.Add(new SqlParameter("#psn", SqlDbType.NVarChar));
update_da.SelectCommand.Parameters["#psn"].Value = yourstringvalue;
var update_ds = new DataSet();
update_da.Fill(update_ds);
'UPDATE' should be used with 'SET' together.
And if you want to update the actual SQL database with the value of edited rows of DataGrid, please try this.
da.UpdateCommand = new SqlCommandBuilder(da).GetUpdateCommand();
da.Update(griddt);
SqlConnection uniConn = null;
SqlCommand cmd = null;
SqlDataAdapter sda = null;
DataTable dt = new DataTable();
uniConn = new SqlConnection(
"server=localhost;" + "Trusted_Connection=yes;" +
"database=Production; " + "connection timeout=30");
cmd = new SqlCommand("UPDATE Budget(id, Name, Quantity, Rate, Time)",
uniConn);
uniConn.Open();
sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
BudgetGrid.ItemsSource = dt.DefaultView;
uniConn.Close();
Did you forget to close the connection?
I am trying to display percentage based on the rank of each record returned in search. I want it to loop through each item but it only loops through the first item as many times as I have items. For instance if it found 4 results it would display the rank of the first one on all 4 results.
Any suggestions to get it to display each rank separately and convert it to percentage?
private void BindRpt()
{
if (string.IsNullOrEmpty(txtSearch.Text)) return;
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString);
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.CommandText = "select Distinct Rank, SUBSTRING(ColumnA, 1, 500) AS ColumnA, ColumnB, ColumnC, ColumnD, ColumnE from FREETEXTTABLE (TABLE , ColumnA, '" + Search.Text + "' ) S, TABLE C WHERE c.ID = S.[KEY] order by Rank Desc";
DataTable dt = new DataTable();
adapter.SelectCommand = cmd;
adapter.Fill(dt);
PagedDataSource pgitems = new PagedDataSource();
pgitems.DataSource = dt.DefaultView;
pgitems.AllowPaging = true;
pgitems.PageSize = 3;
pgitems.CurrentPageIndex = PageNumber;
if (pgitems.Count > 1)
{
rptPaging.Visible = true;
ArrayList pages = new ArrayList();
for (int i = 0; i <= pgitems.PageCount - 1; i++)
{
pages.Add((i + 1).ToString());
}
rptPaging.DataSource = pages;
rptPaging.DataBind();
lblSentence.Visible = true;
lblSearchWord.Visible = true;
lblSearchWord.Text = txtSearch.Text;
}
else
{
rptPaging.Visible = false;
lblSentence.Visible = true;
lblSentence.Text = "Results were found for";
lblSearchWord.Visible = true;
lblSearchWord.Text = txtSearch.Text;
}
rptResults.DataSource = pgitems;
rptResults.DataBind();
cn.Close();
}
protected void rptResults_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["HTAA"].ConnectionString);
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.CommandText = "select Distinct Rank, SUBSTRING(ColumnA, 1, 500) AS ColumnA, ColumnB, ColumnC, ColumnD, ColumnE from FREETEXTTABLE (TABLE , ColumnA, '" + Search.Text + "' ) S, TABLE C WHERE c.ID = S.[KEY] order by Rank Desc";
int number = Page.Items.Count;
SqlDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
int firstrank = dr.GetInt32(0);
while (dr.Read())
{
int rank = dr.GetInt32(0);
int percentage = (rank / firstrank) * 100;
Label lblpre = (Label)e.Item.FindControl("lblRank");
lblpre.Text = percentage.ToString();
}
}
dr.Close();
cn.Close();
}
After a chat, I have a better handle on things. A way to do this;
Create a private field on your code behind file.
private int topRanked = 0;
In your Bind method()
private void Bind()
{
...
DataTable dt = new DataTable();
adapter.SelectCommand = cmd;
adapter.Fill(dt);
topRanked = (int)dt.Rows[0]["Rank"];
Now, make your OnItemDataBound method;
protected void OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
var dataItem = e.Item.DataItem as DataRowView;
int rank = (int) dataItem["Rank"];
var percentage = ((double)topRanked / rank) * 100;
Label label = (Label)e.Item.FindControl("labelRank");
label.Text = percentage.ToString();
}
as mentioned. I don't believe it's the best answer, but it is an answer. I'm sure a stored procedure, or even a better sql method could probably calculate this and not leave you making calculations in code.
Can you try with while(dr.Read()) instead of "if"?
You will want to loop over the result set
while (dr.Read())
{
int rank = dr.GetInt32(0);
int percentage = (rank / rank) * 100;
Label lblpre = (Label)e.Item.FindControl("lblRank");
lblpre.Text = rank.ToString();
}
"but it only loops through the first item" - because you have a for and checks for i <= 0
for (int i = 0; i <= 0; i++)
{
....
}
You just don't need this for statement but rather use
if (dr != null)
using (dr)
{
while (dr.Read())
{
..
}
}
It's always better to use using when dealing with db connection objects so the resources used by these objects are properly disposed after it's been used.
I have code that inserts data into a table when a user enters certain values into three boxes on the page.
The boxes are order number, total weight and tracking reference.
I now need to add further functionality to this code and check first to see if the order number exists, if it does i need to update the columns, if it doesn't I need to insert a new row and add data to that.
I was thinking simply, something like IF results = 0, Insert NEW, ELSE update
How can I modify my code to do this?
protected void Page_Load(object sender, EventArgs e)
{
errorLabel.Visible = false;
successLabel.Visible = false;
errorPanel.Visible = false;
}
protected void submitBtn_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
int _orderID = Convert.ToInt32(orderID.Text);
string _trackingID = trackingNumber.Text;
DateTime _date = DateTime.UtcNow;
int _weightID = Convert.ToInt32(weightID.Text);
SqlConnection myConnection = new SqlConnection("Data Source=localhost\\Sqlexpress;Initial Catalog=databasename;User ID=username;Password=password");
SqlCommand myCommand = new SqlCommand("INSERT into Shipment (TrackingNumber, OrderId, ShippedDateUtc, CreatedOnUtc, TotalWeight) VALUES (#tracking, #order, #date, #date, #weight)", myConnection);
try
{
myConnection.Open();
myCommand.Parameters.AddWithValue("#order", _orderID);
myCommand.Parameters.AddWithValue("#tracking", _trackingID);
myCommand.Parameters.AddWithValue("#date", _date);
myCommand.Parameters.AddWithValue("#weight", _weightID);
int rowsUpdated = myCommand.ExecuteNonQuery();
myConnection.Close();
if (rowsUpdated > 0)
{
alertdiv.Attributes.Add("class", "alert alert-success form-signin");
successLabel.Text = "Thank you, tracking details have been updated";
successLabel.Visible = true;
errorPanel.Visible = true;
}
else
{
alertdiv.Attributes.Add("class", "alert alert-error form-signin");
errorLabel.Text = "Oh dear, the order number is not recognised, please check and try again";
errorLabel.Visible = true;
errorPanel.Visible = true;
}
orderID.Text = "";
trackingNumber.Text = "";
weightID.Text = "";
}
catch (Exception f)
{
errorLabel.Text = "This order number does not exist, please check";
errorLabel.Visible = true;
errorPanel.Visible = true;
return;
}
}
}
protected void Signout_Click(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Response.Redirect("Login.aspx");
}
You can add some SELECT query before your INSERT statement. So if the SELECT query returns more than one row, it means that you already have that record in the DB, and need to update. So, in general it will be like
SqlCommand cmdCount = new SqlCommand("SELECT count(*) from Shipment WHERE OrderId = #order", myConnection);
cmdCount.Parameters.AddWithValue("#order", _orderID);
int count = (int)cmdCount.ExecuteScalar();
if (count > 0)
{
// UPDATE STATEMENT
SqlCommand updCommand = new SqlCommand("UPDATE Shipment SET TrackingNumber = #tracking, ShippedDateUtc = #date, TotalWeight = #weight", myConnection);
updCommand.Parameters.AddWithValue("#order", _orderID);
updCommand.Parameters.AddWithValue("#tracking", _trackingID);
updCommand.Parameters.AddWithValue("#date", _date);
updCommand.Parameters.AddWithValue("#weight", _weightID);
int rowsUpdated = myCommand.ExecuteNonQuery();
}
else
{
// INSERT STATEMENT
SqlCommand insCommand = new SqlCommand("INSERT into Shipment (TrackingNumber, OrderId, ShippedDateUtc, CreatedOnUtc, TotalWeight) VALUES (#tracking, #order, #date, #date, #weight)", myConnection);
insCommand.Parameters.AddWithValue("#order", _orderID);
insCommand.Parameters.AddWithValue("#tracking", _trackingID);
insCommand.Parameters.AddWithValue("#date", _date);
insCommand.Parameters.AddWithValue("#weight", _weightID);
int rowsUpdated = myCommand.ExecuteNonQuery();
}
Edit:
Or much shorter:
SqlCommand command;
if (count > 0)
{
command = new SqlCommand("UPDATE Shipment SET TrackingNumber = #tracking, ShippedDateUtc = #date, TotalWeight = #weight WHERE OrderId = #order", myConnection);
}
else
{
command = new SqlCommand("INSERT into Shipment (TrackingNumber, OrderId, ShippedDateUtc, CreatedOnUtc, TotalWeight) VALUES (#tracking, #order, #date, #date, #weight)", myConnection);
}
command.Parameters.AddWithValue("#order", _orderID);
command.Parameters.AddWithValue("#tracking", _trackingID);
command.Parameters.AddWithValue("#date", _date);
command.Parameters.AddWithValue("#weight", _weightID);
int rowsUpdated = command.ExecuteNonQuery();
The most efficient way would be to put the functionality into a Stored Procedure, for instance (pseudo-code):
IF EXISTS(SELECT * FROM Orders WHERE OrderNo = #orderNo)
UPDATE ...
ELSE
INSERT ...
If you cannot create a new stored procedure, you can also create a command that contains this Statement though readability is typically worse.
Both approaches require only one DB-request.
If you like receive all data and check if exist any record use HasRows.
using (SqlConnection connection = new SqlConnection("server name"))
{
SqlCommand cmd = new SqlCommand("select * From Shipment where OrderId =#OrderId", connection);
connection.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.HasRows==true)//check have any recorder
{
while (sdr.Read())
{
Debug.Print("Exist recorder, example.: "+sdr["_trackingID"]);
}
}
else
{
Debug.Print("not exist recorder");
}
connection.Close();
}