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;
}
Related
I have a website where the admin can delete or add new gridview. For example, if i currently have gridview for giordano products and wanted to change the brand to bossini products. When the admin clicked edit button, the whole gridview and code for giordano products should be removed and if i'm already in update mode and changed the brand name to "bossini" and clicked update, It should add new gridview and code for bossini products.
Now here's the problem. When i do click the edit button, it will remove the whole gridview code but the gridview itself still appears in the website. I finally know that i need to refresh the page but i don't know the best way yet. I have tried Response.Redirect("urls") in GuitarBrandsGridView_RowEditing, but it is not working and it is giving me an exception. It works for GuitarBrandsGridView_RowDeleting tho. I just assumed that maybe it would work for my edit button but it failed.
My goal is, when i click the edit button in gridview, the whole webpage should refresh and then proceed to update mode. Hope this makes sense.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
bindgridviewguitarbrands();
BindGridViewDataList.GetItemsLoad();
}
}
//Start of Gridview Code for Guitar Brands
private void bindgridviewguitarbrands()
{
con1.Open();
cmd1.CommandText = "SELECT * FROM [guitarBrands]";
cmd1.Connection = con1;
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
da1.Fill(ds1);
con1.Close();
GuitarBrandsGridView.DataBind();
}
protected void GuitarBrandsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string name = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Name"));
Button button = (Button)e.Row.FindControl("GuitarBrandsGridViewBtnDelete");
button.Attributes.Add("onclick", "JavaScript:return ConfirmationBox('" + name + "' )");
}
}
protected void GuitarBrandsGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = Convert.ToInt32(GuitarBrandsGridView.DataKeys[e.RowIndex].Value.ToString());
Label name = (Label)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("lblName");
RemoveCodeToGuitarFile.RemoveAddGuitarClass(name.Text);
RemoveCodeToGuitarFile.RemoveConnectionClassGuitarItems(name.Text);
RemoveCodeToGuitarFile.RemoveOverviewGuitarDataASPX(name.Text);
RemoveCodeToGuitarFile.RemoveOverviewGuitarDataCode(name.Text);
File.Delete(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItems" + id + ".aspx");
File.Delete(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItems" + id + ".aspx.cs");
ConnectionClassGuitarBrands.RemoveGuitarBrandsDatabase(name.Text);
con1.Open();
cmd1.CommandText = "DELETE FROM [guitarBrands] WHERE id=" + id;
cmd1.Connection = con1;
int a = cmd1.ExecuteNonQuery();
con1.Close();
if (a > 0) {
bindgridviewguitarbrands();
}
Response.Redirect("~/Pages/OverviewGuitarData.aspx");
}
protected void GuitarBrandsGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
GuitarBrandsGridView.EditIndex = e.NewEditIndex;
string id = GuitarBrandsGridView.DataKeys[e.NewEditIndex].Value.ToString();
Label name = (Label)GuitarBrandsGridView.Rows[e.NewEditIndex].FindControl("lblName");
RemoveCodeToGuitarFile.RemoveAddGuitarClass(name.Text);
RemoveCodeToGuitarFile.RemoveConnectionClassGuitarItems(name.Text);
RemoveCodeToGuitarFile.RemoveOverviewGuitarDataASPX(name.Text);
RemoveCodeToGuitarFile.RemoveOverviewGuitarDataCode(name.Text);
File.Delete(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItems" + id + ".aspx");
File.Delete(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItems" + id + ".aspx.cs");
ConnectionClassGuitarBrands.RemoveGuitarBrandsDatabase(name.Text);
bindgridviewguitarbrands();
Response.Redirect("~/Pages/OverviewGuitarData.aspx");//this one is not working
}
// row update event
protected void GuitarBrandsGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// find student id of edit row
string id = GuitarBrandsGridView.DataKeys[e.RowIndex].Value.ToString();
// find updated values for update
TextBox type = (TextBox)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("txtType");
TextBox name = (TextBox)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("txtName");
TextBox image = (TextBox)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("txtImage");
cmd1 = new SqlCommand("UPDATE [guitarBrands] SET Type = '" + type.Text + "', Name = '" + name.Text + "', Image = '" + image.Text + "' WHERE ID = " + id, con1);
con1.Open();
cmd1.ExecuteNonQuery();
con1.Close();
int ID = Convert.ToInt32(id);
ConnectionClassGuitarBrands.CreateGuitarBrandsDatabase(name.Text);
AddCodeToGuitarFile.AddGuitarClassCode(name.Text, ID);
AddCodeToGuitarFile.AddConnectionClassGuitarItems(name.Text);
AddCodeToGuitarFile.AddOverviewGuitarDataASPX(name.Text, ID);
AddCodeToGuitarFile.AddOverviewGuitarDataASPXCode(name.Text);
AddASPXAndCSFileForGuitarBrands.AddFile(name.Text, ID);
GuitarBrandsGridView.EditIndex = -1;
bindgridviewguitarbrands();
}
// cancel row edit event
protected void GuitarBrandsGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
string id = GuitarBrandsGridView.DataKeys[e.RowIndex].Value.ToString();
TextBox name = (TextBox)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("txtName");
int ID = Convert.ToInt32(id);
ConnectionClassGuitarBrands.CreateGuitarBrandsDatabase(name.Text);
AddCodeToGuitarFile.AddGuitarClassCode(name.Text, ID);
AddCodeToGuitarFile.AddConnectionClassGuitarItems(name.Text);
AddCodeToGuitarFile.AddOverviewGuitarDataASPX(name.Text, ID);
AddCodeToGuitarFile.AddOverviewGuitarDataASPXCode(name.Text);
AddASPXAndCSFileForGuitarBrands.AddFile(name.Text,ID);
GuitarBrandsGridView.EditIndex = -1;
bindgridviewguitarbrands();
}
you need not refresh whole page
GuitarBrandsGridView.DataSource = ds1
GuitarBrandsGridView.DataBind();
then will update new data
Response.Redirect("http://localhost:14999/Home/Index");
Where you want your page to refresh you need to give full path of the page it will reload that page.
I hope it will work coz its working for me
In my my project, I wrote a code such that if there is no data in the DGV it should not be updated, but even though data is not there when I click on the row which is empty and comes by default, and then on update button, it is getting updated. Please help me to fix the issue. The code I am using is:
private void btnUpdate_Click(object sender, EventArgs e)
{
if (dataGridView2.SelectedCells.Count == 0 )
{
MessageBox.Show("There are no any records to update");
}
else
{
SqlConnection con = Helper.getconnection();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
cmd.CommandType = CommandType.Text;
string PrjName = txtPrjNmae.Text;
string Description = txtPrjdescription.Text;
DateTime Date = dateUpdate.Value;
dateUpdate.Format = DateTimePickerFormat.Custom;
dateUpdate.CustomFormat = "dd/MM/yy";
string Size = txtPrjSize.Text;
string Manager = txtPrjManager.Text;
cmd.CommandText = "Update Projects set Description='" + Description + "', DateStarted='" + Date + "',TeamSize='" + Size + "',Manager='" + Manager + "' where ProjectName= '" + PrjName + "' ";
MessageBox.Show("Project Details are updated");
dataGridView2.Update();
dataGridView2.Refresh();
cmd.ExecuteNonQuery();
con.Close();
}
BindData3();
}
You can prevent user from adding new row by click on the last row of datagridview via settig AllowUserToAddRows = false
Check this
dataGridView2.Rows.Count > 0
in a condition
Instead of checking if (dataGridView2.SelectedCells.Count == 0 )
Do this
if( dataGridView2.Rows.Count > 0)
{
}
This will only do conditions if there is more than 0 rows.
first set
dataGridView2.AllowUserToAddRows = false
or
check every time while updating.
dataGridView2.Rows.Count > 0
or
if(dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue.ToString() != " ")
//do ur update here
Since you are letting the users to insert row through a different form (not through grdiview) first hide the empty row which is displayed by default as AllowUserToAddRow property is set to true, You have to set this property to false.
Still if you are allowing the users to add empty row to the grid in some other way then you have to validate it when user click update button. One approach i could think of is,
Check if the selected row has one of the mandatory cell value. Assume ProjectName is mandatory value then you can write a logic as follows,
selectedRow.Cells["ProjectName"] here ProjectName is column name.
private void btnUpdate_Click(object sender, EventArgs e)
{
//Get the selected row
DataGridViewRow selectedRow = dataGridView1.SelectedRows[0];
//Check if Project Name cell in the selected row null or empty
if (string.IsNullOrWhiteSpace(selectedRow.Cells["ProjectName"].Value.ToString()))
{
MessageBox.Show("There are no any records to update");
}
else
{
}
}
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
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