I have searched a lot and failed to and finally arrived here...
I am creating a checkboxList dynamically from the database successfully. Then I want to submit these selcted checked items, I am unable to access. Please find the code....
protected void CreateCheckBoxListDynamically()
{
DataTable dt = new DataTable();
SqlConnection dBConnection = null;
try
{
dBConnection = new SqlConnection();
dBConnection.ConnectionString = ConfigurationManager.ConnectionStrings["***"].ConnectionString;
SqlDataAdapter dataAdapter = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("SP_GetDomesticCountryList", dBConnection);
cmd.CommandType = CommandType.StoredProcedure;
if (ddlTournamentType.SelectedValue != "Select" && ddlTournamentType.SelectedValue != "")
cmd.Parameters.Add("#TournamentId", SqlDbType.Int).Value = Convert.ToInt32(ddlTournamentType.SelectedValue);
else
cmd.Parameters.Add("#TournamentId", SqlDbType.Int).Value = DBNull.Value;
dBConnection.Open();
dataAdapter.SelectCommand = cmd;
dataAdapter.Fill(dt);
if (dt.Rows.Count > 0)
{
CheckBoxList cblCountry = new CheckBoxList();
cblCountry.ID = "cblCountryTeam";
cblCountry.DataTextField = dt.Columns["CT_CountryTeamName"].ToString();
cblCountry.DataValueField = dt.Columns["CT_CountryTeamId"].ToString();
cblCountry.DataSource = dt;
cblCountry.DataBind();
//phCheckBoxList.Attributes.Add("class", "groupbox");
phCheckBoxList.Controls.Add(cblCountry);
phCheckBoxList.Controls.Add(new LiteralControl("<br />"));
}
dBConnection.Close();
}
catch (Exception Ex)
{
throw Ex;
}
finally
{
// Close data reader object and database connection
if (dBConnection.State == ConnectionState.Open)
dBConnection.Close();
}
}
protected void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = null;
SqlConnection dBConnection = new SqlConnection();
SqlDataAdapter dataAdapter = new SqlDataAdapter();
string countryTeamIds = "";
try
{
dBConnection.ConnectionString = ConfigurationManager.ConnectionStrings["***"].ConnectionString;
cmd = new SqlCommand("SP_AddNewSeries", dBConnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#MemberId", SqlDbType.Int).Value = memberId;
if (ddlTournamentType.SelectedValue != "Select")
cmd.Parameters.Add("#TournamentId", SqlDbType.Int).Value = Convert.ToInt32(ddlTournamentType.SelectedValue);
else
cmd.Parameters.Add("#TournamentId", SqlDbType.Int).Value = DBNull.Value;
if (!string.IsNullOrEmpty(txtSeriesStartDate.Text))
cmd.Parameters.Add("#SeriesStartDate", SqlDbType.Date).Value = Convert.ToDateTime(txtSeriesStartDate.Text);
else
cmd.Parameters.Add("#SeriesStartDate", SqlDbType.Date).Value = DBNull.Value;
if (!string.IsNullOrEmpty(txtSeriesEndDate.Text))
cmd.Parameters.Add("#SeriesEndDate", SqlDbType.Date).Value = Convert.ToDateTime(txtSeriesEndDate.Text);
else
cmd.Parameters.Add("#SeriesEndDate", SqlDbType.Date).Value = DBNull.Value;
// get values from dynamic controls
CheckBoxList cb = (CheckBoxList)phCheckBoxList.FindControl("cblCountryTeam");
if (cb != null)
{
foreach (ListItem li in cb.Items)
{
if (li.Selected)
countryTeamIds += li.Value + "~";
}
}
if (!string.IsNullOrEmpty(countryTeamIds))
cmd.Parameters.Add("#CountryTeamIds", SqlDbType.NVarChar).Value = countryTeamIds;
else
cmd.Parameters.Add("#CountryTeamIds", SqlDbType.NVarChar).Value = DBNull.Value;
dBConnection.Open();
dataAdapter.InsertCommand = cmd;
int i = cmd.ExecuteNonQuery();
//hdnseriesId.Value = cmd.Parameters["#SeriesId"].Value.ToString();
if (i == 0)
{
msgNoRecords.Visible = true;
}
else
{
msgNoRecords.Visible = false;
//Response.Redirect("~/country.aspx", false);
}
dBConnection.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
// Close data reader object and database connection
cmd.Dispose();
cmd = null;
if (dBConnection.State == ConnectionState.Open)
dBConnection.Close();
}
}
As per you code details object phCheckBoxList has created in aspx page.
If i am right then this will create problem adding checkboxs at server side.
why dont you create only checkbox at server side rather than checkboxLIST.
After creating checkbox you can add is <div>(this has to be declared at aspx page). this <div> should have an ID and make it runat="server" so you can get this.
After doing above task you can easy find every checkbox from that div at server side code.
Related
I'm having a trouble with my code.
I'm trying to have the user the ability to submit his email to subscribe to my "notify me" service, I havn't code anything lately so I a bit confused..
I'm trying to Insert, Read, and Update data in my Online SQL Server.. but nothing seems to work! I don't know why I tried everything I know I check a million times it seems good.
Plus if there is any errors my catch should show it to me but even that doesn't work :(
Take a look at this maybe your eyes will see something I don't see.
protected void btnSubmit_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["notifyCS"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
try
{
string checkEmail = "SELECT User_Email FROM tbl_users WHERE User_Email = #User_Email";
string checkSubscription = "SELECT User_Status FROM tbl_users WHERE User_Email = #User_Email";
string submitEmail = "INSERT INTO tbl_users (User_UID, User_Email, User_Status) VALUES (#User_UID, #User_Email, #User_Status)";
string submitEmail2 = "UPDATE tbl_users SET User_UID = #User_UID, User_Status = #User_Status WHERE User_Email = #User_Email";
SqlCommand emailCMD = new SqlCommand(checkEmail, conn);
SqlDataAdapter emailSDA = new SqlDataAdapter
{
SelectCommand = emailCMD
};
DataSet emailDS = new DataSet();
emailSDA.Fill(emailDS);
//if there is no email registered.
if (emailDS.Tables[0].Rows.Count == 0)
{
SqlCommand registerEmail = new SqlCommand(submitEmail, conn);
string User_UID = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
registerEmail.Parameters.AddWithValue("#User_UID", HttpUtility.HtmlEncode(User_UID));
registerEmail.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
registerEmail.Parameters.AddWithValue("#User_Status", HttpUtility.HtmlEncode("subscribed"));
registerEmail.ExecuteNonQuery();
registerEmail.Dispose();
conn.Close();
conn.Dispose();
email.Text = null;
}
else if (emailDS.Tables[0].Rows.Count > 0)
{
using (SqlCommand checkSub = new SqlCommand(checkSubscription, conn))
{
checkSub.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
SqlDataReader sdr = checkSub.ExecuteReader();
if (sdr.HasRows)
{
string res = sdr["User_Status"].ToString();
if (res != "subscribed")
{
using (SqlCommand registerEmail2 = new SqlCommand(submitEmail2, conn))
{
string User_UID = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
registerEmail2.Parameters.AddWithValue("#User_UID", HttpUtility.HtmlEncode(User_UID));
registerEmail2.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
registerEmail2.Parameters.AddWithValue("#User_Status", HttpUtility.HtmlEncode("subscribed"));
registerEmail2.ExecuteNonQuery();
registerEmail2.Dispose();
conn.Close();
conn.Dispose();
email.Text = null;
}
}
else
{
conn.Close();
conn.Dispose();
Response.Redirect("index.aspx");
}
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}
}
}
Try it this way:
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
string checkEmail = "SELECT * FROM tbl_users WHERE User_Email = #User";
SqlCommand emailCMD = new SqlCommand(checkEmail, conn);
emailCMD.Parameters.Add("#User", SqlDbType.NVarChar).Value = email.Text;
SqlDataAdapter da = new SqlDataAdapter(emailCMD);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
DataTable emailRecs = new DataTable();
emailRecs.Load(emailCMD.ExecuteReader());
DataRow OneRec;
if (emailRecs.Rows.Count == 0)
{
OneRec = emailRecs.NewRow();
emailRecs.Rows.Add(OneRec);
}
else
{
// record exists
OneRec = emailRecs.Rows[0];
}
// modify reocrd
OneRec["User_UID"] = User_UID;
OneRec["User_Email"] = email.Text;
OneRec["User_Status"] = "subscribed";
email.Text = null;
da.Update(emailRecs);
}
}
I have 50 different format repeaters. Each has to be bind according to the state.
I created a gridview with checkboxes. Whichever rows are checked to display those rows data in the corresponding repeater.
I am sending to the stored procedure multiple parameter and return a datatable. I loop through the datatable and on button click I get all repeaters except when the state is the same - it returns only the last one. I debug and the code runs through it but overwrites the previous row that had that state. How can I display all repeaters for the same state?
protected void GetVinData()
{
SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["DBConnection"]);
SqlCommand cmmd = new SqlCommand();
cmmd.CommandType = CommandType.StoredProcedure;
cmmd.CommandText = c
cmmd.Connection = cn;
cn.Open();
try
{
cmmd.Parameters.Add("#POLICY", SqlDbType.VarChar);
cmmd.Parameters["#POLICY"].Value = ddlPolicy.SelectedValue;
cmmd.Parameters.Add("#VIN", SqlDbType.VarChar);
cmmd.Parameters["#VIN"].Value = txtMsg.Value;
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmmd);
adapter.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["DBConnection"]);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetAllVinNumbers";
cmd.Connection = conn;
cmd.Parameters.Add("#POLICY", SqlDbType.VarChar);
cmd.Parameters["#POLICY"].Value = ddlPolicy.SelectedValue;
cmd.Parameters.Add("#VIN", SqlDbType.VarChar);
cmd.Parameters["#VIN"].Value = dr["VIN"].ToString();
if (dr["STATE"].ToString() == "AL")
{
try
{
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
Repeater_AL.DataSource = cmd.ExecuteReader();
Repeater_AL.DataBind();
Repeater_AL.Visible = true;
conn.Close();
conn.Dispose();
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
lblMessage.Visible = true;
}
finally
{
conn.Close();
conn.Dispose();
}
}
else if (dr["STATE"].ToString() == "AK")
{
try
{
if (conn.State != ConnectionState.Open)
conn.Open();
Repeater_AK.DataSource = cmd.ExecuteReader();
Repeater_AK.DataBind();
Repeater_AK.Visible = true;
conn.Close();
conn.Dispose();
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
lblMessage.Visible = true;
}
finally
{
conn.Close();
conn.Dispose();
}
}
else if (dr["STATE"].ToString() == "AZ")
{
try
{
if (conn.State != ConnectionState.Open)
conn.Open();
Repeater_AZ.DataSource = cmd.ExecuteReader();
Repeater_AZ.DataBind();
Repeater_AZ.Visible = true;
conn.Close();
conn.Dispose();
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
lblMessage.Visible = true;
}
finally
{
conn.Close();
conn.Dispose();
if (Repeater_AZ.Visible == true)
{
Repeater_AZ.Visible = true;
}
}
} ... and so on for 50 states
This slight refactoring may help:
protected void BindVin(string state)
{
Repeater rpt = null;
Control ctl = null;
string name = string.Empty;
SqlConnection conn = null;
SqlCommand cmd = null;
name = "Repeater_" + state;
ctl = Page.FindControl(name);
rpt = ctl as Repeater;
if (rpt != null) {
try {
conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings("DBConnection"));
cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetAllVinNumbers"; // should this have the state to get VINs for?
cmd.Connection = conn;
cmd.Parameters.Add("#POLICY", SqlDbType.VarChar);
cmd.Parameters("#POLICY").Value = ddlPolicy.SelectedValue;
cmd.Parameters.Add("#VIN", SqlDbType.VarChar);
cmd.Parameters("#VIN").Value = dr("VIN").ToString();
if (conn.State != ConnectionState.Open) {
conn.Open();
}
rpt.DataSource = cmd.ExecuteReader();
rpt.DataBind();
rpt.Visible = true;
conn.Close();
conn.Dispose();
} catch (Exception ex) {
lblMessage.Text = ex.Message;
lblMessage.Visible = true;
} finally {
conn.Close();
conn.Dispose();
}
}
}
protected void GetVinData()
{
SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["DBConnection"]);
SqlCommand cmmd = new SqlCommand();
cmmd.CommandType = CommandType.StoredProcedure;
cmmd.CommandText = c
cmmd.Connection = cn;
cn.Open();
try
{
cmmd.Parameters.Add("#POLICY", SqlDbType.VarChar);
cmmd.Parameters["#POLICY"].Value = ddlPolicy.SelectedValue;
cmmd.Parameters.Add("#VIN", SqlDbType.VarChar);
cmmd.Parameters["#VIN"].Value = txtMsg.Value;
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmmd);
adapter.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
BindVin(dr["STATE"].ToString());
}
}
}
I have a windows form of controls combobox and datetimepicker..
I have given null or empty to combobox in page load..
so combobox shows empty intially while loading database values to it in windows form..
but the problem is
because of the datetimepicker is not kept to null or empty my form is showing message box as "the day is already existed" before form is desplaying..here my code follows
I want to show that message after combobox value is selected..
try
{
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
SqlCommand cmd = new SqlCommand("select employee_id,employee_name from Employee_Details", cn);
SqlDataReader dtr;
dtr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("employee_id", typeof(string));
dt.Columns.Add("employee_name", typeof(string));
dt.Load(dtr);
comboBox1.DisplayMember = "employee_id";
comboBox1.DisplayMember = "employee_name";
comboBox1.DataSource = dt;
comboBox1.SelectedItem = null;
if(comboBox1.SelectedItem == null)
{
txtemployeeid.Text = "";
txtemployeename.Text = "";
}
cn.Close();
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
try
{
SqlCommand cmd = new SqlCommand("select employee_id,Employee_name from Employee_Details where employee_name=('" + comboBox1.Text + "')", cn);
SqlDataReader dtr;
dtr = cmd.ExecuteReader();
if (dtr.Read())
{
string employee_id = (string)dtr["employee_id"];
string employee_name = (string)dtr["employee_name"];
txtemployeeid.Text = employee_id;
txtemployeename.Text = employee_name;
dtr.Close();
}
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
if (comboBox1.SelectedItem != null)
{
try
{
string dtp = dateTimePicker1.Value.ToString("dd/MM/yyyy");
SqlCommand cmd1 = new SqlCommand("select date from dailyattendance where date=('" + dtp + "') and employee_id='" + txtemployeeid.Text + "' and empployee_name='" + txtemployeename.Text + "' ", cn);
SqlDataReader dtr1;
dtr1 = cmd1.ExecuteReader();
if (dtr1.Read())
{
string date = (string)dtr1["date"];
if (dtp == date)
{
MessageBox.Show("this day is already existed");
}
}
dtr1.Close();
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
}
cn.Close();
}
can any one solve it please..Thanx in advance
You can simply use dtr.Text="";
Reading this documentation I was unde the impression that the following code would work:
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.C_Str))
{
try
{
using (SqlCommand cmd = new SqlCommand("PerformSearch", con))
{
cmd.CommandType = CommandType.StoredProcedure;
string SearchString = textBoxSearchSting.Text;
cmd.Parameters.Add("SearchString", SqlDbType.VarChar).Value = SearchString;
con.Open();
dataGridView1.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
}
catch (Exception) { throw; }
finally { con.Close(); }
}
Or that I could atleast use the following:
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.C_Str))
{
try
{
using (SqlCommand cmd = new SqlCommand("PerformSearch", con))
{
cmd.CommandType = CommandType.StoredProcedure;
string SearchString = textBoxSearchSting.Text;
cmd.Parameters.Add("SearchString", SqlDbType.VarChar).Value = SearchString;
con.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
dataGridView1.DataSource = reader;
}
}
catch (Exception) { throw; }
finally { con.Close(); }
}
but niether of the above work. Using the below code does work, with the same search value, is the below the best way to fill my datagridview with my query though? And why won't either of the above work?
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.C_Str))
{
try
{
using (SqlCommand cmd = new SqlCommand("PerformSearch", con))
{
cmd.CommandType = CommandType.StoredProcedure;
string SearchString = textBoxSearchSting.Text;
cmd.Parameters.Add("SearchString", SqlDbType.VarChar).Value = SearchString;
con.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader(CommandBehavior.CloseConnection));
if (dt.Rows.Count > 0 && dt != null)
{
dataGridView1.DataSource = dt;
}
}
}
catch (Exception) { throw; }
finally { con.Close(); }
}
Below also works, would I be better of using a data adapter, for any reason?
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.C_Str))
{
try
{
using (SqlCommand cmd = new SqlCommand("PerformSearch", con))
{
cmd.CommandType = CommandType.StoredProcedure;
string SearchString = textBoxSearchSting.Text;
cmd.Parameters.Add("SearchString", SqlDbType.VarChar).Value = SearchString;
DataTable dt = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
con.Open();
da.Fill(dt);
if (dt.Rows.Count > 0 && dt != null)
{
dataGridView1.DataSource = dt;
}
}
}
}
catch (Exception) { throw; }
finally { con.Close(); }
}
I know how to connect, open, read, close as you see below. I also have awesome tutorial how to add update/delete etc.
I can connect dataTable to sql using asp.net controls, but I want to learn how to manipulate it from C#.
MasterCust is my gridview table name. How do I connect the to it?
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection Conn = new SqlConnection("Data Source=aserver;Initial Catalog=KennyCust;Persist Security Info=True;user id=sa;pwd=qwerty01");
SqlDataReader rdr = null;
string commandString = "SELECT * FROM MainDB";
try
{
Conn.Open();
SqlCommand Cmd = new SqlCommand(commandString, Conn);
rdr = Cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0]);
}
}
finally
{
if (rdr != null)
{
rdr.Close();
}
if (Conn != null)
{
Conn.Close();
}
}
//MasterCust.
//MasterCust.DataSource = commandString;
//MasterCust.DataBind();
}
Edit: This code worked
try
{
Conn.Open();
SqlCommand Cmd = new SqlCommand(commandString, Conn);
SqlDataAdapter sdp = new SqlDataAdapter(Cmd);
DataSet ds = new DataSet();
sdp.Fill(ds);
//rdr = Cmd.ExecuteReader();
MasterCust.DataSource = ds.Tables[0];
MasterCust.DataBind();
}
Set the GridView's Datasource property and simply call the DataBind method.
This code will work. ( Tested)
SqlConnection Conn = new SqlConnection("Data Source=Localhost\\SQLEXPRESS;Initial Catalog=Flash2;Integrated Security=True;");
SqlDataReader rdr = null;
string commandString = "SELECT * FROM USER_MASTER";
try
{
Conn.Open();
SqlCommand Cmd = new SqlCommand(commandString, Conn);
rdr = Cmd.ExecuteReader();
MasterCustView.DataSource = rdr;
MasterCustView.DataBind();
}
catch (Exception ex)
{
// Log error
}
finally
{
if (rdr != null)
{
rdr.Close();
}
if (Conn != null)
{
Conn.Close();
}
}