I have controls like TextBox, DropDownList and button on page.
When I enter data to TextBox, DropDown and if I click on button then it should add to GridView cell's TextBox and DropDownList respectively.
Example, When I enter the data to text box and hit the save button, I need to show it to GridView.
No data from DB.
May i know how to do it? Any Example code for reference ? Kindly advise, thank you
Put another button to insert data into database and write below code on click event.
protected void Button2_Click(object sender, EventArgs e)
{
foreach (GridViewRow oItem in GridView1.Rows)
{
string str1 = oItem.Cells[0].Text;
string str2 = oItem.Cells[1].Text;
string str3 = oItem.Cells[2].Text;
insertData(str1, str2, str3);
}
}
public void insertData(string str1,string str2,string str3)
{
SqlConnection cn = new SqlConnection("Your Connection strig");
string sql = "insert into tbl1 (column1,column2,column3) values ('" + str1 + "','" + str2 + "','" + str3 + "')";
SqlCommand cmd = new SqlCommand(sql, cn);
cmd.ExecuteNonQuery();
}
Thanks
Related
I am trying to create a Windows Form App using C# and SQL Server 2012.
My app has two text-boxes, a button and three group-boxes each having three check-boxes. I want the app to be getting the values of check-boxes that are checked, and saving all data to one row in SQL Server.
Example:
ID int PK not null,
Customer_Name varchar(50)
Item_Name nvarchar(max) null
Item_Model nvarchar(max) null
Item_Color nvarchar(max) null
I have created 3 Group boxes to the form each having 3 check boxes:
GroupBox1:
CheckBox1 - name : chkboxLaptop
CheckBox2 - name : chkboxDesktop
CheckBox1 - name : chkboxMonitor
GroupBox2:
CheckBox1 - name : chkboxDell
CheckBox2 - name : chkboxHp
CheckBox1 - name : chkboxLenovo
GroupBox3:
CheckBox1 - name : chkboxSilver
CheckBox2 - name : chkboxGrey
CheckBox1 - name : chkboxBlack
I want the Demo_Table table to look like this:
ID Customer_Name Item_Name Item_Model Item_Color
1 Mulenga Laptop Lenovo Black
Here is my Code:
private void btnAdd_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conString);
StringBuilder name = new StringBuilder();
foreach (Control ctrl in this.groupBox1.Controls)
{
if (ctrl is CheckBox)
{
if (((CheckBox)ctrl).Checked == true)
{
name.Append(((CheckBox)ctrl).Text.ToString() + " ");
con.Open();
SqlCommand sqlcmd = new SqlCommand("INSERT INTO Demo_Table (ID,Customer_Name,Item_Name) VALUES ( '" + txtBoxID.Text.ToString() + "','" + txtBoxName.Text.ToString() + "','" + ((CheckBox)ctrl).Text.ToString() + "')", con);
sqlcmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data added to table");
}
}
}
}
The App is giving me these results:
ID Customer_Name Item_Name Item_Model Item_Color
1 Mulenga Laptop NULL NULL
How do I add data in the Item_Model and Item_Color columns?
Your Assistance will be greatly appreciated.
(as xxbbcc said, never concatenate command text and always use parameters)
To achieve this, you can do something like this (comments in code)
Bear in mind that this code assumes that only one checkbox per group is selected and it will get first selected checkbox text. It would be better to use RadioButtons instead of CheckBoxes.
private void btnAdd_Click(object sender, EventArgs e)
{
//find all checkbox controls in group, get selected one and get its text.
string name = groupBox1.Controls.OfType<CheckBox>().FirstOrDefault(cb => cb.Checked).Text;
string model = groupBox2.Controls.OfType<CheckBox>().FirstOrDefault(cb => cb.Checked).Text;
string color = groupBox3.Controls.OfType<CheckBox>().FirstOrDefault(cb => cb.Checked).Text;
//connection
SqlConnection con = new SqlConnection(conString);
//command text (WITH PARAMETERS!)
string cmdText =
#"
INSERT INTO Demo_Table
(ID,Customer_Name,Item_Name, item_model, item_color)
VALUES
(#id, #customer_name, #item_name, #item_model, #item_color)
";
SqlCommand cmd = new SqlCommand(cmdText, con);
//add params
cmd.Parameters.Add("#id", SqlDbType.VarChar).Value = txtBoxID.Text;
cmd.Parameters.Add("#customer_name", SqlDbType.VarChar).Value = txtBoxName.Text;
cmd.Parameters.Add("#item_name", SqlDbType.VarChar).Value = name;
cmd.Parameters.Add("#item_model", SqlDbType.VarChar).Value = model;
cmd.Parameters.Add("#item_color", SqlDbType.VarChar).Value = color;
//execute query
sqlcmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data added to table");
}
if you have additional questions, feel free to ask.
i have a add product function. after adding those, it will then be viewed. along with the view function is a delete and update link. it works perfectly fine. When i click on the update, textboxes are visible for editing. again, it works fine. but what i want to do is to add validations to it. like if the value should only contain a number, then it will restrict any characters to that update. here is my code behind:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int userid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lblID = (Label)row.FindControl("lblID");
//TextBox txtname=(TextBox)gr.cell[].control[];
TextBox textName = (TextBox)row.Cells[0].Controls[0];
TextBox textDesc = (TextBox)row.Cells[1].Controls[0];
TextBox textQuantity = (TextBox)row.Cells[3].Controls[0];
TextBox textProductPrice = (TextBox)row.Cells[4].Controls[0];
//TextBox textadd = (TextBox)row.FindControl("txtadd");
//TextBox textc = (TextBox)row.FindControl("txtc");
GridView1.EditIndex = -1;
conn.Open();
//SqlCommand cmd = new SqlCommand("SELECT * FROM detail", conn);
SqlCommand cmd = new SqlCommand("update Products set ProductName='" + textName.Text + "',ProductDescription='" + textDesc.Text + "',ProductQuantity='" + textQuantity.Text + "',ProductPrice ='" + textProductPrice.Text + "'where ProductID='" + userid + "'", conn);
cmd.ExecuteNonQuery();
conn.Close();
gvbind();
//GridView1.DataBind();
}
any ideas on what can i do to add validations. the reason for this is that when i try to input for example "abc" to the
TextBox textQuantity = (TextBox)row.Cells[3].Controls[0];
it gives me an error that it cannot be converted. please help. thanks!
You have to find control on each of the gridview row
Below is an example
TextBox textQuantity = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtBoxId");
if (string.IsNullOrEmpty(textQuantity .Text))
{
//Validation failed
return;
}
i have three text boxes for telephone number mobile number and for age;
i enter the details there and insert them in to the database. after insert how can i make textboxes cleared. it won't allow me to do so coz insert method is like this
public void insert(int mobile,int telephone,int age)
{
try
{
MySqlConnection asp= new MySqlConnection(conString);
asp.Open();
string insertString = "insert into users(mob,tele,age) values('"+mobile+"','"+telephone+"','"+age+"')
MySqlCommand cmd = new MySqlCommand(insertString,asp);
dr = cmd.ExecuteReader();
MessageBox.Show("New user added succesfully","Information");
//afteer this how to empty the three textboxes
// ihave used these three as integers in database
}
calling method is
insert(int.parse(textbox1text),int.parse(textbox2.text),int.parse(textbox3.text))
You can use TextBox.Clear() method to clear the contents of the TextBox after the Insert()statement
Try This:
insert(int.parse(textbox1.Text),int.parse(textbox2.Text),int.parse(textbox3.Text));
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
After Calling Insert method Just use this
insert(int.parse(textbox1text),int.parse(textbox2.text),int.parse(textbox3.text));
textBox1.Text =String.Empty;
textBox2.Text =String.Empty;
textBox3.Text =String.Empty;
(or)
insert(int.parse(textbox1text),int.parse(textbox2.text),int.parse(textbox3.text));
textBox1.Text ="";
textBox2.Text ="";
textBox3.Text ="";
I am trying to delete the row in the grid view. For that one i am writing code in the rowdeleting event like below.
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string UserId;
SqlTransaction tran;
using (con = new SqlConnection())
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["EMASFBAConnectionString"].ConnectionString;
cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
tran = con.BeginTransaction();
TableCell cell = GridView1.Rows[e.RowIndex].Cells[1];
string username = cell.Text;
cmd.Transaction = tran;
cmd.CommandText = "Delete from aspnet_Users where UserName='" + username + "'";
UserId = cmd.ExecuteScalar().ToString();
if (UserId.Length!=0)
{
//delete user from membership table.
errorLabel.Text = "User is ready to delete";
}
tran.Commit();
con.Close();
}
}
when i debug the cell value is coming as empty. What i did the mistake here?
This grid view has edit and delete button in front of the each row.
I tried with Cells[0],Cells[2] but giving the empty values only. Can any one give me the solution?
hi define datakeys in the gridview and use this method
string UserID = GridView1.DataKeys[e.RowIndex].Value.ToString();
and then based on this ID delete the row.
cmd.CommandText = "Delete from aspnet_Users where UserID=" + UserID;
after that call your databind method to bind the gridview with updated records
for datakeynames please use this
<asp:gridview datakeynames="UserID"
runat="server">
Finally got the answer. If i try to get the values as Table cells it is not giving proper values. So i tried like this,
GridViewRow row = GridView1.Rows[e.RowIndex];
Label usernamelable = (Label)row.FindControl("lblUserNameValue");
string username = usernamelable.Text;
This works fine for me. I am referring the label control inside the gridview and getting the value.
try the following code:
var empId = Convert.ToInt32(this.gvDetails.DataKeys[e.RowIndex].Values["EmpId"].ToString());
protected void NPNGridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow gvr = NPNGridView1.SelectedRow;
TextBox1.Text = gvr.Cells[1].Text;
}
it's working, before u run the solution, please once test this Cells[1] indexes,
I have 2 Panels on one page(SAPInfo, OSInfo). In SAPInfo panel there are 3 textboxes(SID, Client,User_id) and 1 SEARCH button. After clicking SEARCH button i want to display data of SAP table(user_id,Descriptio,sap_system_password) in Gridview on the next page. Similarly In OSInfo panel there are 2 text boxes(IP/HostName,User_id) and 1 SEARCH button. After clicking SEARCH button i want to display data of OS table(user_id,Descriptio,os_system_password) in the same Gridview. The Gridview has 4 columns(UserID,Description,Password,Change Password) SAP table contains fields as(sid,client_no,user_id,sap_system_password,description) OS table contains fields as(user_id,ip,host_name,os_system_password,description)
How to do this? Please help..
this is my Search button(SAP) code
protected void btnSAPSearch_Click(object sender, EventArgs e)
{
try
{
using (MySqlConnection conn = new MySqlConnection(clsUser.connStr))
{
conn.Open();
string strQuery = "select DISTINCT user_id,description,sap_system_password from sap_password_info where user_id is not null";
if (txtSid.Text !="")
{
strQuery += " AND sid = '" + txtSid.Text + "'";
}
if (txtClient.Text != "")
{
strQuery += " AND client_no = '" + txtClient.Text + "'";
}
if (txtUser.Text != "")
{
strQuery += " AND user_id = '" + txtUser.Text + "'";
}
MySqlCommand cmd = new MySqlCommand(strQuery, conn);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader(CommandBehavior.CloseConnection));
Session["userinfo"] = dt;
Response.Redirect("~\\PasswordInformation_Details.aspx");
}
}
catch (Exception ex)
{
//lblMessage.Text = DataObjects.Error_Message();
lblMsg.Text = ex.Message.ToString();
}
}
The solution is pretty simple. Pass the search criteria as query string to your other page.
So on click of search button(SAP Panel) build a query string like following
//if sap
string url = "Result.aspx?Mode=SAP&sid=some_sid&client=some_client&user_id=some_user_id;
Response.Redirect(url, false);
So on click of search button(OS Panel)
//if OS
string url = "Result.aspx?Mode=OS&ip=some_ip&user_id=some_userId;
Response.Redirect(url, false);
ON result page page_load
if(Request.QueryString["Mode"] =="SAP")
{
//bring sap result dataset
}
else
{
// bring os result dataset
}
//bind it to gridView
resultGridView.DataSource = dsResult
resultGridView.DataBind();
Keep in mind. make the autogeneratedcolumn = true on the grid view. Now your grid view would display whatever result would be given to it(3 column, 4 columns).The columns would be dynamically generated now.
EDIT 1
After search, you would have some dataset with the result. To change the grid header, simply change the column name in the dataTable. What ever column you would give, would be displayed by the grid
datatable.Columns["original_column_name"].ColumnName = "new column name";
//For adding a new column, just simply do this to your result set
datatable.Columns.Add("Change Password");
EDIT 2
string strQuery = "select DISTINCT user_id as User Id,description as Description,sap_system_password as Sap System Password from sap_password_info where user_id is not null";
Also see this : Column Alias