I have a form in ASP.NET that loads data if it exists for the user, and then allows them to update. So in Page_Load I have:
protected void Page_Load(object sender, EventArgs e)
{
if (!CheckAndAddRecord(_currentUser.UserID))
{
CreateEntryPoint(_currentUser.UserID);
}
else
{
DataView dv = LoadApplicationData(_currentUser.UserID);
foreach (DataRowView rowView in dv)
{
DataRow row = rowView.Row;
_applicationId = row["id"].ToString();
txtProjectNumber.Text = row["ProjectNumber"].ToString();
if (String.IsNullOrEmpty(chkSignedNDANo.ToString()) || String.IsNullOrEmpty(chkSignedNDAYes.ToString()))
{
chkSignedNDANo.Checked = Convert.ToBoolean(row["SignedNDAOnFile"]);
chkSignedNDAYes.Checked = Convert.ToBoolean(row["SignedNDAOnFile"]);
}
txtDateWritten.Text = row["DateWritten"].ToString();
}
}
}
It calls this method:
public bool CheckAndAddRecord(int UserId)
{
string connStr = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("CheckUserInTemp", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#SubmittedBy", UserId));
SqlDataAdapter dap = new System.Data.SqlClient.SqlDataAdapter(cmd);
DataSet ds = new DataSet();
// open conn
if (conn.State == ConnectionState.Closed)
conn.Open();
// fill
dap.Fill(ds);
// close the conn
if (conn.State == ConnectionState.Open)
conn.Close();
bool boolRecordExist = false;
if (ds.Tables[0].DefaultView.Count == 0)
{
boolRecordExist = false;
}
else
{
boolRecordExist = true;
}
return boolRecordExist;
}
This seems to work and populate the fields correctly. But then to update I call a Button click, which calls this method:
public void UpdateRecordInTemp(int appId, string projectNumber)
{
string connStr = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("CPC_ProposalUpdateTemp", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", appId);
cmd.Parameters.AddWithValue("#ProjectNumber", txtProjectNumber.Text);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new Exception("Exception adding coupon. " + ex.Message);
}
finally
{
conn.Close();
}
}
The problem is the fields passed always contain the old values. So if the value when entering the page is "123" and I change it to "abc" and click the button, "123" is passed instead of "abc".
Sorry for the long post, I wanted to get all the details in. I am baffled by this. Thanks!
At page Load check IsPostBack property in if. It seems that your code is executing on every page load.
if(!IsPostBack)
{
// Do your work
}
UPDATE
In your code method UpdateRecordInTemp(int appId, string projectNumber) you are not using projectNumber instead you are using txtProjectNumber.Text
Related
I want to display data in a datagrid based on value selected in a ComboBox but my datatable function returns null and nothing is displayed in the datagrid.
public DataTable ReadData(User user)
{
using (SqlConnection db = new SqlConnection(AppConnect.Connection))
{
string query = "SELECT moduleCode,moduleName,modCredits,modHrsLeft FROM [Module] WHERE userName=#userName";
try
{
using (SqlCommand command = new SqlCommand(query, db))
{
if (db.State == ConnectionState.Closed)
{
db.Open();
command.Parameters.AddWithValue("#userName", user.UserName);
SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
table = new DataTable();
dataAdapter.Fill(table);
}
}
db.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return table;
}
}
This function is in a class library. The function is called in the WPF project, this is the code:
private void BtnDisplay_Click(object sender, RoutedEventArgs e)
{
string userName = CmboxUserN.SelectedItem.ToString();
User user1 = new User
{
UserName = userName
};
DataTable table = data.ReadData(user1);
gridModules.DataContext= table;
}
Try these changes. It seems that the line table = new DataTable(); is never being hit. You don't need to check to make sure the connection is in a closed state because you are using a using statement.
public DataTable ReadData(User user)
{
using (SqlConnection db = new SqlConnection(AppConnect.Connection))
{
string query = "SELECT moduleCode,moduleName,modCredits,modHrsLeft FROM [Module] WHERE userName=#userName";
try
{
using (SqlCommand command = new SqlCommand(query, db))
{
db.Open();
command.Parameters.AddWithValue("#userName", user.UserName);
SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
table = new DataTable();
dataAdapter.Fill(table);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return table;
}
}
Also, you don't need to .Close() the connection because the SqlConnection is in a using statement, which means the object will be disposed of when the scope of the using statement is exited.
One other tip: You should change the code to have the try catch around everyting and if there are any errors at all, log the errors to console and return a new DataTable().
i am creating c# project so far insert and delete buttons are working but when i hit update button it gives data has not been updated and i cant see what is wrong with my code please help
public bool Update(Classre c)
{
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstring);
try
{
string sql = "UPDATE Class SET ClassName=#ClassName,ClassLevel=#ClassLevel WHERE ClassID=#ClassID";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#ClassName", c.ClassName);
cmd.Parameters.AddWithValue("#ClassLevel", c.ClassLevel);
conn.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
isSuccess = true;
}
else
{
isSuccess = false;
}
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
return isSuccess;
}
and this is my update button code where i call the class that holds my update code
private void button3_Click(object sender, EventArgs e)
{
c.ClassID = int.Parse(textBox1.Text);
c.ClassName = textBox2.Text;
c.ClassLevel = comboBox1.Text;
bool success = c.Update(c);
if (success == true)
{
// label4.Text = "Data Has been updated";
MessageBox.Show("Data Has been updated");
DataTable dt = c.Select();
dataGridView1.DataSource = dt;
}
else
{
//label4.Text = "Data Has not been updated";
MessageBox.Show("Data Has not been updated");
}
}
I would prefer to use a stored procedure instead of pass through sql but you could greatly simplify this. As stated above your try/catch is worse than not having one because it squelches the error.
public bool Update(Classre c)
{
USING(SqlConnection conn = new SqlConnection(myconnstring))
{
string sql = "UPDATE Class SET ClassName = #ClassName, ClassLevel = #ClassLevel WHERE ClassID = #ClassID";
USING(SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add("#ClassName", SqlDbType.VarChar, 4000).Value = c.ClassName;
cmd.Parameters.Add("#ClassLevel", SqlDbType.Int).Value = c.ClassLevel;
cmd.Parameters.Add("#ClassID", SqlDbType.Int).Value = c.ClassID;
conn.Open();
int rows = cmd.ExecuteNonQuery();
return rows > 0;
}
}
}
I have a datagridview displayng a table of products, everything is working just fine, inserting, updating and deleting. But the dgv only updates if I click on it. How can I make it update on load and after I click the buttons of insert, delete and update?
DGV enter method:
// this is where i call the select method in the main form
private void dataGridView1_Enter(object sender, EventArgs e)
{
// sisDBADM is the class that holds all the sql querys
sisDBADM obj = new sisDBADM();
dataGridView1.DataSource = obj.ListaGrid();
}
public DataTable ListaGrid()
{
vsql = "SELECT NOME , PRECO FROM menu";
NpgsqlCommand objcmd = null;
if (this.conectar())
{
try
{
objcmd = new NpgsqlCommand(vsql, con);
NpgsqlDataAdapter adp = new NpgsqlDataAdapter(objcmd);
DataTable dt = new DataTable();
adp.Fill(dt);
return dt;
}
catch (NpgsqlException e)
{
throw e;
}
finally
{
this.desconectar();
}
}
else
{
return null;
}
}
Insert method:
public bool Insert(ArrayList p_arrInsert)
{
vsql = "INSERT INTO menu(nome,preco)" + "VALUES(#nome,#preco)";
NpgsqlCommand objcmd = null;
// conection try/catch adding the parameters
if (this.conectar())
{
objcmd = new NpgsqlCommand(vsql, con);
objcmd.Parameters.Add(new NpgsqlParameter("#nome", p_arrInsert[0]));
objcmd.Parameters.Add(new NpgsqlParameter("#preco", p_arrInsert[1]));
objcmd.ExecuteNonQuery();
return true;
}
else
{
return false;
}
}
Remove dataGridView1_Enter method and call ListaGrid method from insert, delete and update button click event.
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=*******;Initial Catalog=ChatApp;User ID=Chatapplication;Password=****";
conn.Open();
SqlCommand cmd = new SqlCommand();
string chatroomidno = textBox1.Text;
string chatroomname = textBox2.Text;
//cmd.CommandText = "Select ChatRoomID=#ChatRoomID,ChatRoomName=#ChatRoomName from tblChatRoom";
//cmd.Connection = conn;
SqlDataAdapter adapt = new SqlDataAdapter("Chatroomapp",conn);
adapt.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds=new DataSet();
DataTable dt = new DataTable();
adapt.SelectCommand.Parameters.Add(new SqlParameter("#ChatRoomID", SqlDbType.VarChar, 100));
adapt.SelectCommand.Parameters["#ChatRoomID"].Value = chatroomidno;
adapt.SelectCommand.Parameters.Add(new SqlParameter("#ChatRoomName", SqlDbType.VarChar, 50));
adapt.SelectCommand.Parameters["#ChatRoomName"].Value = chatroomname;
adapt.Fill(ds, "tblChatRoom");
if (dt.Rows.Count > 0)
{
MessageBox.Show("Connection Succedded");
}
else
{
MessageBox.Show("Connection Fails");
}
}
catch (Exception ex)
{
MessageBox.Show("Error", ex.Message);
}
}
While compiling the program I got only connection fails message box, in the database. I found correct, how to overcome the program to get the connection succeeded message box.
Well, you're filling the ds data set - but then you're checking the dt data table for presence of rows... that's never going to work, of course!
If you only need a single DataTable - just use and fill that data table alone - no need for the overhead of a DataSet. Also, put your SqlConnection and SqlCommand into using blocks like this:
using (SqlConnection conn = new SqlConnection("Data Source=*******;Initial Catalog=ChatApp;User ID=Chatapplication;Password=****"))
using (SqlCommand cmd = new SqlCommand("Chatroomapp", conn))
{
string chatroomidno = textBox1.Text;
string chatroomname = textBox2.Text;
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
adapt.SelectCommand.CommandType = CommandType.StoredProcedure;
adapt.SelectCommand.Parameters.Add(new SqlParameter("#ChatRoomID", SqlDbType.VarChar, 100));
adapt.SelectCommand.Parameters["#ChatRoomID"].Value = chatroomidno;
adapt.SelectCommand.Parameters.Add(new SqlParameter("#ChatRoomName", SqlDbType.VarChar, 50));
adapt.SelectCommand.Parameters["#ChatRoomName"].Value = chatroomname;
// fill the data table - no need to explicitly call `conn.Open()` -
// the SqlDataAdapter automatically does this (and closes the connection, too)
DataTable dt = new DataTable();
adapt.Fill(dt);
if (dt.Rows.Count > 0)
{
MessageBox.Show("Connection Succedded");
}
else
{
MessageBox.Show("Connection Fails");
}
}
And just because you get back no rows in dt.Rows doesn't necessarily mean that your connection failed..... it could just be that there are no rows that match your search critieria! The connection worked just fine - but the SQL command just didn't return any rows.
Connection failed means that something went wrong between your program and the database. No records returned does not mean that the connection failed. It just means that your table is empty - it contains no records.
Using ADO.NET and a stored procedures would have been a little different from what you have done it. If you need to check if the connection failed, maybe it is better to check the type of exception that is returned in the catch part.
Below is how I would have done it. I would have created a separate method that would have handled my call, and then in your button1_Click I would have just called this method:
public async Task<ChatRoom> GetAsync(string chatRoomId, string chatRoomName)
{
try
{
string connectionString = ConfigurationManager.ConnectionStrings["Db"].ConnectionString;
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
await sqlConnection.OpenAsync();
using (SqlCommand sqlCommand = new SqlCommand("ChatRooms_Get", sqlConnection))
{
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add(new SqlParameter("#ChatRoomID", chatRoomId));
sqlCommand.Parameters.Add(new SqlParameter("#ChatRoomName", chatRoomName));
using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
{
ChatRoom chatRoom = null;
if (await sqlDataReader.ReadAsync())
{
chatRoom = new ChatRoom();
chatRoom.Id = sqlDataReader.GetFieldValue<string>(0);
chatRoom.Name = sqlDataReader.GetFieldValue<string>(1);
chatRooms.Add(chatRoom);
}
return chatRoom;
}
}
}
}
catch (Exception exception)
{
// Try checking if the connection failed here
throw exception;
}
}
My chat room domain model could have looked like this:
public class ChatRoom
{
public string Id { get; set; }
public string Name { get; set; }
}
And the stored procedure would have looked like this:
CREATE PROCEDURE [dbo].[ChatRooms_Get]
(
#ChatRoomID VARCHAR(100),
#ChatRoomName VARCHAR(50)
)
AS
BEGIN
SET NOCOUNT ON;
SELECT
ChatRoomID,
ChatRoomName
FROM
tblChatRoom
WHERE
ChatRoomID = #ChatRoomID
AND ChatRoomName = #ChatRoomName;
END
GO
And then in the calling method you would get the chatroom and do with it whatever you need to do with it. For this example I just checked if it exists or not:
try
{
ChatRoom chatRoom = await chatRoomRepository.GetAsync(chatRoomId, chatRoomName);
if (chatRoom != null)
{
MessageBox.Show("Record found");
}
else
{
MessageBox.Show("No record found");
}
}
catch (Exception exception)
{
throw exception;
}
I hope this can help.
I'm making a gallery site. And it plots the available photography sessions that are on the database.
But when the user first opens the page, no photography sessions are selected. So the page would be empty. I want to automatically select the first session for the user. I did it by selecting the first record in the database. But i really wish if i could just write a code inside the Page_load that auto clicks on the first item inside the repeater.
The repeater items are dynamically generated of course. So i don't know if i could achieve this using JavaScript or not.
Here's my code :
protected void Page_Load(object sender, EventArgs e)
{
DataSet dst = new DataSet();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString))
{
SqlDataAdapter adbtr = new SqlDataAdapter();
adbtr.SelectCommand = new SqlCommand("SELECT * FROM dbo.Select_gallery_names_FN()", con);
try
{
int result = adbtr.Fill(dst);
if (result == 0)
{
return;
}
cat_repeater.DataSource = dst;
cat_repeater.DataBind();
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
}
using (SqlConnection img_con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString))
{
SqlDataAdapter img_adbtr = new SqlDataAdapter();
img_adbtr.SelectCommand = new SqlCommand("select * from dbo.Select_gallery_cat_FN(#img_cat)", img_con);
img_adbtr.SelectCommand.Parameters.Add("#img_cat",SqlDbType.NVarChar,8000).Value = dst.Tables[0].Rows[0][0].ToString();
DataSet img_dst = new DataSet();
try
{
img_adbtr.Fill(img_dst);
slider_repeater.DataSource = img_dst;
slider_repeater.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
protected void cat_repeater_ItemCommand(object source, RepeaterCommandEventArgs e)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select * from dbo.Select_gallery_cat_FN(#img_cat)";
cmd.Parameters.Add("#img_cat", SqlDbType.NVarChar,8000).Value = ((LinkButton)e.CommandSource).Text;
con.Open();
slider_repeater.DataSource = cmd.ExecuteReader();
slider_repeater.DataBind();
}
}
You could do something like this.
<script>
$(document).ready(function() {
$('#cat_repeaterId').find('tr:first').click();
});
</script>
Might have to mess around with the javascript depending on if you want to click a button inside the first row.