Convert Rank to percentage C# - c#

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.

Related

Updating DATAGRID row to save to SQL

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?

Date-picker using select statement oracle

I'm trying to implement date-picker functionality in my project, but I can't do it quite right. I'm trying to pass the date-picker value in my oracle string so that it will compare with my db column and return results on the date criteria...
Whenever I pass it to the select statement it won't generate errors particularly but on button click it doesn't perform anything except it shows "not connected".
str = "Select * from sania.doctor where APPOINTMENT_DATE = "+ datepicker1.value;
It is clear it is logical mistake but I'm new to this C# concepts I need someone to tell me how to pass it and then display the results as well.
private void button1_Click(object sender, EventArgs e)
try
{
OracleCommand com;
OracleDataAdapter oda;
string ConString = "Data Source=XE;User Id=system;Password=sania;";
OracleConnection con = new OracleConnection(ConString);
{
// string id = dateTimePicker1.Text.Trim();
con.Open();
// str = "Select * from sania.doctor where APPOINTMENT_DATE = " + dateTimePicker1.value;
str = "select * from sania.doctor where APPOINTMENT_DATE to_date('"+dateTimePicker1.Value.ToString("yyyyMMdd") + "', 'yyyymmdd')";
com = new OracleCommand(str);
oda = new OracleDataAdapter(com.CommandText, con);
dt = new DataTable();
oda.Fill(dt);
Rowcount = dt.Rows.Count;
//int val = 0;
for (int i = 0; i < Rowcount; i++)
{
dt.Rows[i]["APPOINTMENT_DATE"].ToString();
//if (id == dateTimePicker1.Value)// this LINE SHOWS ERROR--because it is a string and I am using date with it. Don't know conversion
// {
// val = 1;
//}
}
// if (val == 0)
// { MessageBox.Show("INVALID ID"); }
// else
// {
DataSet ds = new DataSet();
oda.Fill(ds);
if (ds.Tables.Count > 0)
{
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
else { MessageBox.Show("NO RECORDS FOUND"); }
}
}
//}
catch (Exception)
{ MessageBox.Show("not connected"); }
}
Do not put values into SQL directly, use bind variables/parametes instead. For Oracle:
// :prm_Appointment_Date bind variable declared within the query
String str =
#"select *
from sania.doctor
where Appointment_Date = :prm_Appointment_Date";
....
using(OracleCommand q = new OracleCommand(MyConnection)) {
q.CommandText = str;
// datepicker1.Value passed into :prm_Appointment_Date via parameter
q.Parameters.Add(":prm_Appointment_Date", datepicker1.Value);
...
}
Doing like that you can be safe from either SQL Injection or Format/Culture differences

using a button max 3 times before disabling it

I want to be able to use this button to search oracle three times at most and after the three attempts to disable the button and use a different search. Below is my code when the button is clicked to search first. If the catch is used three times I want to be able to disable the button.
private void btnCancelSearch_Click(object sender, EventArgs e)
{
try
{
//Connect to Database
OracleConnection conn = new OracleConnection(oradb);
conn.Open();
OracleCommand cmd = conn.CreateCommand();
//Define SQL Query (Select)
strSQL = "SELECT * FROM Bookings WHERE BookingNo = '" + txtCnlBookingNo.Text + "'";
cmd.CommandText = strSQL;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
txtBookingNo.Text = dr.GetValue(0).ToString();
txtBkgSurname.Text = dr.GetValue(1).ToString();
txtBkgForename.Text = dr.GetValue(2).ToString();
txtBkgContactNo.Text = dr.GetValue(3).ToString();
txtBkgStreet.Text = dr.GetValue(4).ToString();
txtBkgTown.Text = dr.GetValue(5).ToString();
txtBkgCounty.Text = dr.GetValue(6).ToString();
txtBkgCountry.Text = dr.GetValue(7).ToString();
txtBkgEmail.Text = dr.GetValue(8).ToString();
cboBkgNoGuests.Text = dr.GetValue(9).ToString();
cboBkgPayment.Text = dr.GetValue(10).ToString();
dtpBkgCheckIn.Text = dr.GetValue(11).ToString();
dtpBkgCheckOut.Text = dr.GetValue(12).ToString();
}
catch
{
//Display confirmation message
MessageBox.Show("Not a valid Booking No");
}
Depending on your application. You can keep track of a variable called:
int ButtonClickedCount = 0;
increment this variable everytime the button is clicked. If the click count is exceeded you notify the user or disable the button.
Not sure if this is what you trying to achieve:
Declare a variable to keep track of the number of times user have clicked, then apply your logic?
int count = 0;
private void btnCancelSearch_Click(object sender, EventArgs e)
{
if(count <3){
count++;
try
{
//Connect to Database
OracleConnection conn = new OracleConnection(oradb);
conn.Open();
OracleCommand cmd = conn.CreateCommand();
//Define SQL Query (Select)
strSQL = "SELECT * FROM Bookings WHERE BookingNo = '" + txtCnlBookingNo.Text + "'";
cmd.CommandText = strSQL;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
txtBookingNo.Text = dr.GetValue(0).ToString();
txtBkgSurname.Text = dr.GetValue(1).ToString();
txtBkgForename.Text = dr.GetValue(2).ToString();
txtBkgContactNo.Text = dr.GetValue(3).ToString();
txtBkgStreet.Text = dr.GetValue(4).ToString();
txtBkgTown.Text = dr.GetValue(5).ToString();
txtBkgCounty.Text = dr.GetValue(6).ToString();
txtBkgCountry.Text = dr.GetValue(7).ToString();
txtBkgEmail.Text = dr.GetValue(8).ToString();
cboBkgNoGuests.Text = dr.GetValue(9).ToString();
cboBkgPayment.Text = dr.GetValue(10).ToString();
dtpBkgCheckIn.Text = dr.GetValue(11).ToString();
dtpBkgCheckOut.Text = dr.GetValue(12).ToString();
}
catch
{
//Display confirmation message
MessageBox.Show("Not a valid Booking No");
}
}else
{
//Implement whatever search you want here
//And disable your button here
}
}

Removing duplicates in a MS Access database

I was trying to remove duplicates from the table Main.
It looks like this(here in csv form):
"Record ID";Status;Placement;Private;Category;Note;Blob
for instance
14341692;132;2147483647;False;4;"29.12.10 14:17";System.Byte[]
Duplicates means, Note is the same. My approach is this:
string strSQL = "SELECT * FROM Main";
OleDbCommand cmd = new OleDbCommand(strSQL, MemoVerbindung);
OleDbDataReader dr = cmd.ExecuteReader();
_items = new List<string>(); // <-- Add this
while (dr.Read())
{
if (dr.FieldCount >= 5)
_items.Add(dr[5].ToString());
}
dr.Close();
progressBar1.Maximum = _items.Count;
for (int a = 0; a < _items.Count; a++)
{
progressBar1.Value = a;
strSQL = "SELECT * FROM Main WHERE Note = '" + _items[a].ToString().Replace("'", "\'") + "'";
cmd = new OleDbCommand(strSQL, MemoVerbindung);
dr = null;
OleDbDataReader dr2 = null;
try
{
dr = cmd.ExecuteReader();
int u = 0;
if (dr.FieldCount > 1)
{
while (dr.Read())
{
if (u >= 1)
{
string was = "DELETE FROM Main WHERE [Record ID] = " + dr[0];
OleDbCommand command = new OleDbCommand(was, MemoVerbindung);
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//MessageBox.Show(reader[0].ToString());
}
reader.Close();
}
u++;
}
}
else
{
while (dr.Read())
{
MessageBox.Show("Übrig");
}
}
dr.Close();
}
catch (Exception mm)
{
//MessageBox.Show(mm.Message);
}
}
MessageBox.Show("Fertig");
progressBar1.Value = 0;
So in the if (u >= 1) section I am trying to leave one version while removing all others. Unfortunately that does not work meaning all entries are removed but the ones raising an error for a reason. What would you change or is there a generally more elegant way?
Use this SQL statement to find the duplicates:
SELECT First(Main.[Note]) AS [NoteField], Count(Main.[Note]) AS NumberOfDups
FROM Main
GROUP BY Main.[Note]
HAVING (((Count(Main.[Note]))>1));
then you can loop through this recordset (grab it as a SnapShot so changes to the underlying data does not change the results)
use !NoteField to know which note to find, and !NumberOfDups to know how many you have to delete (remove this number - 1)

How to implement Edit Feature in asp.net application?

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";
}

Categories

Resources