Trigger Click event on the first repeater item - c#

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.

Related

DataTable returns null WPF

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().

Page_Load() load data don't go away

I am working on a visual web part that does simple CRUD operations and I have this strange behavior in Page_load().
I grab first record from query and assign some text fields when page is loaded. When I clear the form and update the form with new different inputs, those text fields remember the first values and ignores newly entered data.
Am I missing anything in Page_load() when I display data when the page is loaded?
public partial class VisualWebPart1UserControl : UserControl
{
string connstr = AdminDashBoard.Utility.GetConnectionString();
private DataSet sqlDst = new DataSet();
private static int RowNo = 0;
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(connstr);
string strQuery = "xxxxxxxxxxxxxxxxxxxxxx";
try
{
conn.Open();
SqlCommand sqlCmd = new SqlCommand(strQuery, conn);
sqlCmd.CommandType = CommandType.Text;
SqlDataAdapter sqlAdap = new SqlDataAdapter(sqlCmd);
sqlAdap.Fill(sqlDst);
//these fields remember first assigned data!!!
this.TextBox1.Text = sqlDst.Tables[0].Rows[RowNo][0].ToString();
this.TextBox2.Text = sqlDst.Tables[0].Rows[RowNo][1].ToString();
this.TextBox3.Text = sqlDst.Tables[0].Rows[RowNo][2].ToString();
this.DateTimeControl1.SelectedDate = Convert.ToDateTime(sqlDst.Tables[0].Rows[RowNo][3].ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
conn.Close();
conn.Dispose();
}
}
thanks in advance

Update mysql database from datagridview selected row

i have a datagridview which loads mysql database table t_pi_clients on form load event,and i have another tab which contains textboxes of the respective columns of t_pi_client, which am able to get data from fullrowselect mode into those textboxes. now i want to update the database upon changes in the those textbox values. so far i've tried some process and gets my "entry saved" messageBox.show but nothing happens to database, so am hoping someone could help me out maybe am missing something thanks
public partial class frmMain : Form
{
MySqlConnection connection;
MySqlDataAdapter mySqlDataAdapter;
DataSet dt = new DataSet();
DataSet DS = new DataSet();
DataSet dg = new DataSet();
public frmMain()
{
InitializeComponent();
}
#region Main load
private void frmMain_Load(object sender, EventArgs e)
{
var connectionString = ConfigurationManager.ConnectionStrings["Pigen"].ConnectionString;
connection = new MySqlConnection(connectionString);
if (this.OpenConnection() == true)
{
mySqlDataAdapter = new MySqlDataAdapter("select * from t_pi_Clients", connection);
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
kryptonDataGridView1.DataSource = DS.Tables[0];
kryptonDataGridView1.Columns[0].Visible = false;
mySqlDataAdapter = new MySqlDataAdapter("select * from t_pi_msg_charge_Rate", connection);
DataSet dt = new DataSet();
mySqlDataAdapter.Fill(dt);
kryptonDataGridView2.DataSource = dt.Tables[0];
mySqlDataAdapter = new MySqlDataAdapter("select * from t_pi_client_deposits", connection);
DataSet dg = new DataSet();
mySqlDataAdapter.Fill(dg);
kryptonDataGridView3.DataSource = dg.Tables[0];
}
}
//loads selected row data into textboxes
private void kryptonDataGridView1_DoubleClick(object sender, EventArgs e)
{
textboxClientCode.Text = kryptonDataGridView1.SelectedRows[0].Cells["ClientCode"].Value.ToString();
txtboxClientName.Text = kryptonDataGridView1.SelectedRows[0].Cells["ClientName"].Value.ToString();
txtboxPostalAddress.Text = kryptonDataGridView1.SelectedRows[0].Cells["PostalAdd"].Value.ToString();
txtboxTelephone.Text = kryptonDataGridView1.SelectedRows[0].Cells["Telephone"].Value.ToString();
txtboxFax.Text = kryptonDataGridView1.SelectedRows[0].Cells["Fax"].Value.ToString();
txtboxEmailAddress1.Text = kryptonDataGridView1.SelectedRows[0].Cells["EmailAdd1"].Value.ToString();
txtboxEmailAddress2.Text = kryptonDataGridView1.SelectedRows[0].Cells["EmailAdd2"].Value.ToString();
txtboxEmailAddress3.Text = kryptonDataGridView1.SelectedRows[0].Cells["EmailAdd3"].Value.ToString();
txtboxWebsite.Text = kryptonDataGridView1.SelectedRows[0].Cells["Website"].Value.ToString();
txtboxChargeRate.Text = kryptonDataGridView1.SelectedRows[0].Cells["ChargeRate"].Value.ToString();
txtboxTotalDepo.Text = kryptonDataGridView1.SelectedRows[0].Cells["TotalDeposit"].Value.ToString();
txtboxAccountBal.Text = kryptonDataGridView1.SelectedRows[0].Cells["AccountBal"].Value.ToString();
txtboxEntrydate.Text = kryptonDataGridView1.SelectedRows[0].Cells["EntryDate"].Value.ToString();
}
now i tried this method to update but doesn't update database
private void kryptonbtnUpdate_Click(object sender, EventArgs e)
{
var connectionString = ConfigurationManager.ConnectionStrings["Pigen"].ConnectionString;
using (MySqlConnection Conn = new MySqlConnection(connectionString))
if (Conn.State.ToString() != "Open")
{
}
else
{
connection.Open();
}
try
{
DataTable changes = ((DataTable)kryptonDataGridView1.DataSource).GetChanges();
if (changes != null)
{
MySqlCommandBuilder mcb = new MySqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.UpdateCommand = mcb.GetUpdateCommand();
mySqlDataAdapter.Update(changes);
((DataTable)kryptonDataGridView1.DataSource).AcceptChanges();
mySqlDataAdapter.Update(DS);
}
// adapter.Update(rowsToUpdate);
// mySqlDataAdapter.Update(DS);
MessageBox.Show("Entry Saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This is just a pseudocode of what you need to do
string cmdText = #"UPDATE t_pi_Clients
SET ClientName = #ClientName,
PostalAdd = #PostalAdd,
Telephone = #Telephone,
Fax = #Fax,
.... etc ....
WHERE ClientCode = #ClientCode";
using(MySqlConnection cn = new MySqlConnection(.....))
using(MySqlCommand cmd = new MySqlCommand(cmdText, cn))
{
cn.Open();
cmd.Parameters.AddWithValue("#ClientName", txtboxClientName.Text);
cmd.Parameters.AddWithValue("#PostalAdd", txtboxPostalAddress.Text);
....etc etc...
cmd.Parameters.AddWithValue("#ClientCode", textboxClientCode.Text);
int rowsUpdated = cmd.ExecuteNonQuery();
if(rowsUpdated > 0)
{
// extract the code that loads DataGridView1 from the Form_Load
// and create a reusable method that you could call from here
}
}
First you build an sql command text with the UPDATE clause. I assume that your primary key (the field that uniquely identifies your records) is the ClientCode field.
Then create the connection and the command. Fill the command parameters collection with the parameters required by your text taking the values from the TextBoxes.
Call the ExecuteNonQuery to store the values.
If you succeed then you need to update or reload your datagridview. The best approach would be setting one by one the gridview cells of the current row with the new values from the textboxes, or you could simply extract the code used in form_load to fill the grid and make a new method that you could call from the button click event. (But this could be slower if you have many records)

Update sql database using dataset

I need some help to complete this. I have searched and tried several ways but is not enetring in my head yet. It is not homework! I am a self learner.
I managed to populate a grid selecting the table from a dropdown:
private void radDropDownList1_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
{
if (radDropDownList1.SelectedIndex > 0)
{
radGridView1.Visible = true;
label8.Text = radDropDownList1.SelectedValue.ToString();
DataTable dt = new DataTable();
var selectedTable = radDropDownList1.SelectedValue; //Pass in the table name
string query = #"SELECT * FROM " + selectedTable;
using (var cn = new SqlConnection(connString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand(query, cn);
using (var da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
catch (SqlException ex)
{
//MessageBox.Show(ex.StackTrace);
}
}
radGridView1.DataSource = dt;
}
Now I am trying to write the event to update the sql table using the grid as datasource:
private void radGridView1_CellEndEdit(object sender, Telerik.WinControls.UI.GridViewCellEventArgs e)
{
DataTable dt = (DataTable)radGridView1.DataSource;
DataSet ds = new DataSet();
ds.Tables[0] = dt;
try
{
//**I am lost here!**
}
catch
{
}
}
Could you please help? How can I now update the sql table?
I don't really like the way you are managing the updates but... this code here will send an update statement:
using (var cn = new SqlConnection(connString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand("UPDATE YourTable SET Column = #Parm1 WHERE Col = #Parm2", cn);
var parm1 = cmd.CreateParameter("Parm1");
parm1.Value = "SomeValue";
var parm2 = cmd.CreateParameter("Parm2");
parm2.Value = "SomeOtherValue";
cmd.Parameters.Add(parm1);
cmd.Parameters.Add(parm2);
int rowsAffected = cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
//MessageBox.Show(ex.StackTrace);
}
}

Error with loading and updating form data

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

Categories