Get submit button id for query - asp.net

I have a master page in witch more then 30 button like (java,asp,php,sql,c,c++,etc...)
and a have a table of questions. All questions are tagged with one subject like asp,java,etc.
I want to get data according to the click button.
How is it possible?
protected void BindRepeaterData()
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * from question", con);
int count = (int)cmd.ExecuteScalar();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
RepDetails.DataSource = ds;
RepDetails.DataBind();
con.Close();
}
(I think one page for one button is not a good idea.)

There are few ways to capture button click inside Data such as Repeater, GridView, ListView.
Easiest way is to use Command event instead of Click event.
<%-- Let say this button is located inside Repeater control.--%>
<asp:Button ID="DoSomethingButton" runat="server" Text="Home"
OnCommand="DoSomethingButton_Command" CommandArgument="<%# Eval("Id") %>" />
// Retrieve e.CommandArgument from code-behind.
protected void DoSomethingButton_Command(object sender, CommandEventArgs e)
{
int id = Convert.ToInt32(e.CommandArgument);
}

If you want the ID of the button itself, you can cast the sender back to the Button and get it's ID.
protected void Button1_Click(object sender, EventArgs e)
{
Button button = sender as Button;
string id = button.ID;
}

If I understand you question correctly you could select field from the table according to button information for example in this way. And you could use same event handler for different buttons. Hope this helps.
protected void Btn1_Click(object sender, EventArgs e)
{
Button button = sender as Button;
string question = readData(button.Text);
//do further actions
}
private string readData(string subject)
{
string question = string.Empty;
using (SqlConnection con = new SqlConnection(/*connection_string*/))
{
using (SqlCommand cmd = new SqlCommand("SELECT question from question_table where subject = #subject", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#subject", subject);
con.Open();
object o = cmd.ExecuteScalar();
if (o != null){
question = o.ToString();
}
con.Close();
}
}
return question;
}

Related

Submit button to update database, won't work if there is postback stated in page_load

I have a web form page that I am going to query the data from database via selecting different values from dropdown list, after I selected proper value, in the description I want to update the database record while I click the submit button, for example, customer name, and status, there will be only one record coming back and the description will show(I can do it in isPostback and query the database, using SQL DataReader and then call related index element to get it) but when I typed something in the description and click submit, it won't update in the database, but if I don't use if(isPostback) it is working.
P.S. if there is no if(ispostback) case block there,dataUpdate.Update() works well.
So my question is;
protected void btnSubmit_Click(object sender, EventArgs e)
{
dataUpdate.Update();
}
The page_load code:
protected void Page_Load(object sender, EventArgs e)
{
ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
if (!IsPostBack)
{
SqlConnection conn1 = new SqlConnection(cxInfo.ConnectionString);
string userInfoQuery1 = "select * from users where id=#id";
SqlCommand userInfo1 = new SqlCommand(userInfoQuery1, conn1);
userInfo1.Parameters.AddWithValue("#id", dropdlCx.SelectedValue);
conn1.Open();
SqlDataReader reader1 = userInfo1.ExecuteReader();
reader1.Read();
if (reader1.HasRows )
{
lblCxId.Text = "" + reader1[0];
SqlConnection conn = new SqlConnection(dataUpdate.ConnectionString);
string userInfoQuery = "select cx_first_name+',' + cx_last_name as 'name',cx_id ,incident_id,description,contact_method from incident where cx_id=#id and status=#status";
SqlCommand userInfo = new SqlCommand(userInfoQuery, conn);
userInfo.Parameters.AddWithValue("#id", lblCxId.Text);
userInfo.Parameters.AddWithValue("#status", dropStatus.SelectedValue);
conn.Open();
SqlDataReader reader = userInfo.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
lblCxId.Text = "" + reader1[0];
txtDesc.Text = (string)reader[3];
radioContact.SelectedValue = (string)reader[4];
desc= (string)reader[3];
}
conn.Close();
}
conn1.Close();
}
if (IsPostBack)
{
lblCxId.Text = dropdlCx.SelectedValue;
/*I want to have txtDesc.txt= database query here, but as long as I add the code here, then the update won't work*/
}
}
So I think there only thing I got stuck is how to let the system know that what I submit is not the thing that he is going to refresh, please accept my value instead of the refresh?

GridView RowCommand update send variable to javascript function

I have a Gridview that has an update link on it. Once "Edit" is selected from one of the rows the values in that row in the grid change into text boxes and can be edited. The "edit" button disappears and changes into an "update" link. Then the user edits the contents of one (or more than one) of the text boxes and "update" is selected. A JavaScript confirmation box appears asking if the user wants to update the values(s) and the changes are saved or discarded depending upon the choice selected. This is performed by "OnClientClick"
However I want to validate the change server side and pass back a defined error message to the user if the validation has failed. Example; if registered company name in the wrong format has been entered into one of the text boxes in the row selected.
The grid row will then remain in an editable state until the user corrects the error. The operation can be discarded by selecting "Cancel" from the grid row (I already have this functionality).
The C# rowcommand function is:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Update")
{
// get the primary key id of the clicked row
int id = Convert.ToInt32(e.CommandArgument);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["moduleConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE suppliers SET Registered_company_name=#registered_company_name WHERE Supplier_code=#supplier_code;";
System.Web.UI.WebControls.TextBox myTextBox_registered_company_name = GridView1.Rows[id].FindControl("Registered_company_name") as System.Web.UI.WebControls.TextBox;
cmd.Parameters.Add("#registered_company_name", SqlDbType.VarChar).Value = myTextBox_registered_company_name.Text;
System.Web.UI.WebControls.Label myLabel = GridView1.Rows[id].FindControl("suppliercode") as System.Web.UI.WebControls.Label;
cmd.Parameters.Add("#supplier_code", SqlDbType.VarChar).Value = Convert.ToInt32(myLabel.Text);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
BindData();
}
}
The ASPX is
<asp:LinkButton ID="lnkUpdate" runat="server" CommandArgument='<%# Container.DataItemIndex %>' OnClientClick="return ConfirmOnUpdate();" CommandName="Update" > Update</span></asp:LinkButton>
The javascript is
function ConfirmOnUpdate()
{
if (confirm("Are you sure you want to update this record?"))
return true;
else
return false;
}
Thank you for any replies
Use this code for handling server side validation.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Update")
{
// get the primary key id of the clicked row
int id = Convert.ToInt32(e.CommandArgument);
System.Web.UI.WebControls.TextBox myTextBox_registered_company_name = GridView1.Rows[id].FindControl("Registered_company_name") as System.Web.UI.WebControls.TextBox;
if (myTextBox_registered_company_name.Text != "") // add your validation in this if block, now it checks textbox is not empty;
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["moduleConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE suppliers SET Registered_company_name=#registered_company_name WHERE Supplier_code=#supplier_code;";
System.Web.UI.WebControls.TextBox myTextBox_registered_company_name = GridView1.Rows[id].FindControl("Registered_company_name") as System.Web.UI.WebControls.TextBox;
cmd.Parameters.Add("#registered_company_name", SqlDbType.VarChar).Value = myTextBox_registered_company_name.Text;
System.Web.UI.WebControls.Label myLabel = GridView1.Rows[id].FindControl("suppliercode") as System.Web.UI.WebControls.Label;
cmd.Parameters.Add("#supplier_code", SqlDbType.VarChar).Value = Convert.ToInt32(myLabel.Text);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
BindData();
}
else
{
ScriptManager.RegisterStartupScript(this,this.GetType(),"Error Message", "alert('TextBox is empty!')",true);
}
}

how to bind gridview to sqldatasource to our own created form

I have a form and 'Add' button. when i click on add then i insert data into database and also i have sqldatasource in which i specify only select,update,delete commands. when i insert data on Add button then i want to refresh and fill the grid automatically.
my sqldatasource id is "sqldatasourceDenter" and i have specified it in my gridview datasourceID="sqldatasourceDenter".
i have tried this
GridView1.DataSourceID = sqldatasourceDenter;
it gives me the error cannot convert sqldatasource to string
i have also defined datasource but it tells both me both datasource, datasourceID cannot be defined.
I actually want to insert data on my 'Add' button then refresh the sqldataSourceDenter to fill the grid.
This is my add button click event function:
..... add_Click(object sender, EventArgs e){
..
.... /* here i have other code*/
.....
else {
string dentername = dname.Text.ToString();
string denteraddress = daddress.Text.ToString();
string dentercontact = dcontact.Text.ToString();
//create sql inset query and take to insert query ftn for execution
string dquery = string.Format("INSERT INTO Denters(D_NIC, D_Name, D_Address, D_Contact) VALUES('{0}','{1}','{2}','{3}')", denternic, dentername, denteraddress, dentercontact);
InsertIntoDB.InsertQuery(dquery);
if (InsertIntoDB.count > 0)
{
gvDenter.DataSourceID = SqlDataSourceDenter;
Response.Write("<script>alert('Denter added successfully')</script>");
InsertIntoDB.count = 0;
ClearDenterFields();
}
}
}
My aspx code is:
<asp:SqlDataSource ID="SqlDataSourceDenter" runat="server" ConnectionString="<%$ ConnectionStrings:VehiclesSystemConnectionString2 %>"
SelectCommand="SELECT [D_NIC], [D_Name], [D_Address], [D_Contact] FROM [Denters]">
</asp:SqlDataSource>
<asp:GridView ID="gvDenter" Visible="False" DataKeyNames="D_NIC" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSourceDenter" >
</asp:GridView>
You can have something like
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDataToGrid();
}
}
protected void BindDataToGrid()
{
string conString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(conString))
{
string myQuery = "SELECT * FROM MYTABLE";
SqlCommand cmd = new SqlCommand(myQuery);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
protected void Add(object sender, EventArgs e)
{
//Insert To DB Code here
}

I need a DropDown value that is linked to another page

I have a DropDown List where I have brought the values from my Database using code-behind.
I have added a new value after reading data from source, called ".. Add new skill".
Now when user clicks on that item I need a small page (or rather a new page) to open to add the skills that are not mentioned in the DropDownList.
if (!IsPostBack)
{
SqlConnection myConn = new SqlConnection(#"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True");
SqlCommand myCmd = new SqlCommand(
"SELECT SkillName, SkillID FROM Skills", myConn);
myConn.Open();
SqlDataReader myReader = myCmd.ExecuteReader();
//Set up the data binding.
DropDownList1.DataSource = myReader;
DropDownList1.DataTextField = "SKillName";
DropDownList1.DataValueField = "SkillID";
DropDownList1.DataBind();
//Close the connection.
myConn.Close();
myReader.Close();
//Add the item at the first position.
DropDownList1.Items.Insert(0, "..Add New Skill");
}
This is my code-behind file.. How do I link that now?
You should use the SelectedIndexChanged event and SelectedValue property:
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
if(String.Compare(ddl.SelectedValue,"..Add New Skill",true)==0)
Response.Redirect("Add_New_Skill.aspx");
}
Add a SelectedIndexChanged event handler to that dropdown like this
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
if(ddl.SelectedIndex == 0)
Response.Redirect("Add_New_Skill.aspx");
}
If you want position of "...Add new skill" to be at last of the list
Use this
ddl.Items.Insert(ddl.Items.Count, "...Add New Skill");
Now to redirect to another page you should do this
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
if(ddl.SelectedIndex == ddl.Items.Count-1)
Response.Redirect("Add_New_Skill.aspx");
}
Set AutoPostBack to true. That way when the user changes an option, it will automatically post the page to the server.
Handle this SelectedIndexChanged event, and redirect to your add page there.
Take your user to a add page.
Add the details to the database.
Bring the user back to this page.
List will be reloaded from database, and you till get your value.
No special linking is required.
This is working
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindDropdownlist()
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string getvalue = DropDownList1.SelectedItem.Value;
if (getvalue == "..Add New Skill")
{
Response.Redirect("Default.apsx");
}
}
public void bindDropdownlist()
{
SqlDataAdapter dap = new SqlDataAdapter("select coloumn1,colum2 from table", con);
DataSet ds = new DataSet();
dap.Fill(ds);
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataTextField = "coloumn1";
DropDownList1.DataValueField = "colum2 ";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, "..Add New Skill");
}
}
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
</div>

Dropdownlist on gridview updating only first value to the database ASP.Net

I am looking for the solution to this problem from many days, please help.
I have a grid view and have five dropdownlist on it. I have edit update and cancel edit buttons on each row.
Drop down list is updating the database, but only first value in the dropdownlist even when user select second, third or any other value from the dropdownlist.
What could possible be the reason for this. Here is my row Edit/ CancelEdit and Updating Events.
protected void gvCustomers_RowEditing(object sender, GridViewEditEventArgs e)
{
gvCustomers.EditIndex = e.NewEditIndex;
BindData();
}
protected void gvCustomers_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvCustomers.EditIndex = -1;
BindData();
}
protected void gvCustomers_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label lblCustId = (Label)gvCustomers.Rows[e.RowIndex].FindControl("cust_id");
DropDownList ddlCsm = (DropDownList)gvCustomers.Rows[e.RowIndex].FindControl("CSM");
DropDownList ddlSrCsm = (DropDownList)gvCustomers.Rows[e.RowIndex].FindControl("SrCSM");
DropDownList ddlDE = (DropDownList)gvCustomers.Rows[e.RowIndex].FindControl("DE");
DropDownList ddlAE = (DropDownList)gvCustomers.Rows[e.RowIndex].FindControl("AE");
DropDownList ddlTE = (DropDownList)gvCustomers.Rows[e.RowIndex].FindControl("TE");
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
string sql = "Update SOME_TABLE SET CSM= #CSM, SrCSM= #SrCSM ,DE=#DE,AE=#AE,TE=#TE where cust_id=#cust_id";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add("#CSM", SqlDbType.VarChar).Value = ddlCsm.SelectedItem.Value;
cmd.Parameters.Add("#SrCSM", SqlDbType.VarChar).Value = ddlSrCsm.SelectedItem.Value;
cmd.Parameters.Add("#AE", SqlDbType.VarChar).Value = ddlAE.SelectedItem.Value;
cmd.Parameters.Add("#DE", SqlDbType.VarChar).Value = ddlDE.SelectedItem.Value;
cmd.Parameters.Add("#TE", SqlDbType.VarChar).Value = ddlTE.SelectedItem.Value;
cmd.ExecuteNonQuery();
}
}
catch
{ }
gvCustomers.EditIndex = -1;
BindData();
}
}
Any help would be greatly appeciated.
Thanks
just fill the dropdowns on the click of edit button and then use on rowupdating event and use ddl.SelectedValue instead of ddl.SelectedItem.Value. You will find the selected values.
Your Drop Downs are probably getting re-set in your Page_Load event. If they are, load them when the page is not in postback, like so:
if(!Page.IsPostBack) {
//set drop downs
}

Resources