store selected grid view value into database - asp.net

I've a gridview in which a radiobutton is used to select a particular row of data. Now I need to save radio button selected row into database. How do I achieve this? I'm not using JQuery or Ajax, my entire coding is done on ASP.NET

I didn't got your problem correctly,But the ideal methodology is to use Check box instead of Radio button will be far better for your coding purpose.
The below code is a demo for inserting the values into the database from a grid view where in the particular rows will be inserted which has been checked.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["YourConnectionstring"].ToString());
SqlCommand cmd = new SqlCommand();
string active = "N";
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
string A = GridView1.Rows[i].Cells[0].Text;
string B = GridView1.Rows[i].Cells[1].Text;
GridViewRow row = GridView1.Rows[i];
CheckBox Ckbox = (CheckBox)row.FindControl("CheckBox1");
if (Ckbox.Checked == true)
{
cn.Open();
cmd.CommandText = "Insert into table_name(A,B) values (#A,#B)";
cmd.CommandType = CommandType.Text;
cmd.Connection = cn;
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#A", A);
cmd.Parameters.AddWithValue("#B", B);
cmd.ExecuteNonQuery();
cn.Close();
}
}
Hope this will be helpful for you.

Easy
Search through GridRows
FindControl radio button on each row.
Check that button is Checked or not.
and now try it.

Related

How to insert dropdownlist value, text box value and gridviews selected row together?

How to insert dropdownlist value, text box value and gridviews selected row together?
Also attached the screenshot of the data insert:
enter image description here
enter image description here
enter image description here
I tend to prefer a add button that adds a row to the grid, and THEN you let the user edit the one row.
However, assuming you have those text boxes at the top of the screen, enter data, and then click a button to add to the database, and then re-fresh the GV?
I also don't see some button in the top area to add the data?
so, say a button added to the top area?
then this would add the row to the database:
protected void Button3_Click(object sender, EventArgs e)
{
string strSQL =
"INSERT INTO MyTable (Session, Class, Section, Term, Subject, HighestMark) " +
"VALUES (#Session, #Class, #Seciton, #Term, #Subject, #HighestMark)";
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL,conn))
{
conn.Open();
cmdSQL.Parameters.Add("#Session", SqlDbType.Int).Value = DropSession.selecteditem.value;
cmdSQL.Parameters.Add("#Class", SqlDbType.Int).Value = DropClass.selecteditem.value;
cmdSQL.Parameters.Add("#Section", SqlDbType.Int).Value = DropSection.selecteditem.value;
cmdSQL.Parameters.Add("#Term", SqlDbType.Int).Value = DropTerm.selecteditem.value;
cmdSQL.Parameters.Add("#Subject", SqlDbType.Int).Value = DropSubject.selecteditem.value;
cmdSQL.Parameters.Add("#HighestMark", SqlDbType.Int).Value = HighestMark.Text;
cmdSQL.ExecuteNonQuery();
}
}
ReloadGrid(); // call routine to refresh the grid.
}
Edit: Adding the rows to a new table
Ok, so we are to take the top values, and then process each row of the grid, and take the ones with a check box and "insert" this data into a new table.
Ok, so the code will look like this:
protected void Button1_Click(object sender, EventArgs e)
{
string strSQL = "SELECT * FROM tblHotelsA WHERE ID = 0";
DataTable rstData = MyRst(strSQL);
foreach (GridViewRow gRow in GHotels.Rows)
{
CheckBox ckChecked = gRow.FindControl("ckSelected") as CheckBox;
if (ckChecked.Checked)
{
// this row was checked - add a new row
DataRow MyNewRow = rstData.NewRow();
MyNewRow["HotelName"] = txtHOtelName.Text; // exmaple control
MyNewRow["City"] = txtCity.Text; // example control above grid
// values from grid row
// tempalted columns, we use find control
MyNewRow["FirstName"] = (gRow.FindControl("txtFirstName") as TextBox).Text;
MyNewRow["LastName"] = (gRow.FindControl("txtLastName") as TextBox).Text;
// if data bound column, then we use cells collection
MyNewRow["FavorateFood"] = gRow.Cells[5];
// etc. etc.
rstData.Rows.Add(MyNewRow);
}
}
// done adding to table, write/save back to database.
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
SqlDataAdapter da = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
cmdSQL.Connection.Open();
da.Update(rstData);
}
}
}
I also had this helper routine - I often use it all over the palce:
public DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Connection.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
So, the concept here?
I pulled a blank row (SELECT * from table where ID = 0).
This gets me the database structure - and thus avoids a BOATLOAD of parameters in the sql.
this approach ALSO allows me to add a row to the table, and add "many" rows. And then execute ONE update to the database to write out (save) all the rows in one shot. So, this again reduced quite a bit of messy code.

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

Why is not this gridview loading the results?

I am trying to fill the gridview with the search results. Here is the UI of my "AddDropClasses" page:
When this page is loaded, i want the gridview to be filled the current courses of the current user, and i do this using the Register table. Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
con.Open();
string query = "select * from RegisterTable where StudentID='" + MyGlobals.currentID + "'";
SqlDataAdapter adap = new SqlDataAdapter(query, con);
DataTable tab = new DataTable();
adap.Fill(tab);
showCourses.DataSource = tab;
}
I load (come to) this page by clicking a button from another page. The problem is, the table shows no results. When i debugged i realized that Myglobals.ID has the value what i already expect. What can be the problem here? Can anyone help?;
Thanks
You forgot to databind showCourses. Add showCourses.DataBind(); after showCourses.DataSource = tab;

Asp.Net: Is gridview is the only way to display data in data base ??

Is grid is the only way to display data in the data base ??
i want to display the data in a lable.. I this possible for below code.. ??
protected void cnt_btn_Click(object sender, EventArgs e)
{
con = new SqlConnection(Str);
con.Open();
cmd = new SqlCommand("select Count(emp_id) from emp_tbl", con);
dr = cmd.ExecuteReader();
gridview.DataSource = dr;
gridview.DataBind();
con.Close();
}
The above code runs successfully for gridview display.. but i want to display count it in lable tool.. i had tried like this
//lable.Text = Convert.ToString(dr);
//lable.DataBind();
but it's wrong.. pls let me get rid of this problem... thanks..
Why don't you just do this:
lable.Text = dr.GetInt32(0).ToString();

Finding the item in selecteditemchanging event

In listview im showing product information .On each row there is one select button on each row in itemTemplate .
if user click this button i want which bookid is clicked in selectedindexchanging event.
i bound listview like following
string str = "SELECT BookName,BookPrice, Description, bookid FROM productinfo Where Categoryid ='" + Request.QueryString["CategoryId"] + "'";
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd = new SqlCommand(str, conn);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
lstvwShopItems.DataSource = dt;
lstvwShopItems.DataBind();
Please give solution?
in order to get a certain column when selecting a row you need to fill the property datakeynames with the property of your choice.
msdn
getting the value of the property:
void lstvwShopItems_SelectedIndexChanged(Object sender, EventArgs e)
{
string value = lstvwShopItems.SelectedValue;
}
don't forget to set the OnSelectedIndexChanged on your listview to this method in the codebehind..

Resources