How to avoid inserting the unwanted values to database? - c#

I want to insert only the selected value but when I save its inserting all the values in database.
In the above database in subject column I want only the subject which has the faculty.But in my database all the subjects are inserting.
I am using boundfield for the subject column in GridView. My code so far`
<asp:GridView ID="Gvassignsubject" runat="server" AutoGenerateColumns="False" OnRowDataBound="Gvassignsubject_RowDataBound">
<Columns>
<asp:BoundField DataField="Subject" HeaderText="subject" SortExpression="subject" />
<asp:TemplateField HeaderText ="Faculty">
<ItemTemplate>
<asp:Label ID ="lblfaculty" runat="server" Text='<%%# Eval("facultyname") %>>' Visible="false"/>
<asp:DropDownList ID="ddlfaculty" runat="server"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Set Hour">
<ItemTemplate>
<asp:TextBox ID="txthour" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>`
protected void btnsubmit_Click(object sender, EventArgs e)
{
using (SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
foreach (GridViewRow r in Gvassignsubject.Rows)
{
for (int i = 0; i < Gvassignsubject.Rows.Count; i++)
{
string batch = ddlbatches.SelectedValue;
string subject = r.Cells[0].Text;
DropDownList ddlfaculty = (DropDownList)Gvassignsubject.Rows[i].FindControl("ddlfaculty");
TextBox txthour = (TextBox)Gvassignsubject.Rows[i].FindControl("txthour");
string facultyname = ddlfaculty.SelectedValue;
string sethour = txthour.Text;
con2.Open();
SqlCommand cmd = new SqlCommand("insert into assign (batch,facultyname,sethour,subject)values(#batch,#facultyname,#sethour,#subject)", con2);
cmd.Parameters.AddWithValue("#batch", batch);
cmd.Parameters.AddWithValue("#subject", subject);
cmd.Parameters.AddWithValue("#facultyname", facultyname);
cmd.Parameters.AddWithValue("#sethour", sethour);
cmd.Connection = con2;
cmd.ExecuteNonQuery();
con2.Close();
}
}
}
}

Its adding all the rows regardless because you have no criteria;
for (int i = 0; i < Gvassignsubject.Rows.Count; i++)
{
DropDownList ddlfaculty = (DropDownList)Gvassignsubject.Rows[i].FindControl("ddlfaculty");
string facultyname = ddlfaculty.SelectedValue;
if (!string.Equals(ddlfaculty.SelectedValue, "Please Select"))
{
string batch = ddlbatches.SelectedValue;
string subject = r.Cells[0].Text;
TextBox txthour = (TextBox)Gvassignsubject.Rows[i].FindControl("txthour");
string sethour = txthour.Text;
con2.Open();
SqlCommand cmd = new SqlCommand("insert into assign (batch,facultyname,sethour,subject)values(#batch,#facultyname,#sethour,#subject)", con2);
cmd.Parameters.AddWithValue("#batch", batch);
cmd.Parameters.AddWithValue("#subject", subject);
cmd.Parameters.AddWithValue("#facultyname", facultyname);
cmd.Parameters.AddWithValue("#sethour", sethour);
cmd.Connection = con2;
cmd.ExecuteNonQuery();
con2.Close();
}
}

I believe you have to set default select list item value as null and check for it in your for loop:
for (int i = 0; i < Gvassignsubject.Rows.Count; i++)
{
if(!string.IsNullOrEmpty(ddlfaculty.SelectedValue)) {
...
}
}

You can put a condition that will check the value exist or not in the subject field. You can do this like below :
if(facultyname !="" && facultyname !="Please Select")
{
SqlCommand cmd = new SqlCommand("insert into assign (batch,facultyname,sethour,subject)values(#batch,#facultyname,#sethour,#subject)", con2);
cmd.Parameters.AddWithValue("#batch", batch);
cmd.Parameters.AddWithValue("#subject", subject);
cmd.Parameters.AddWithValue("#facultyname", facultyname);
cmd.Parameters.AddWithValue("#sethour", sethour);
cmd.Connection = con2;
cmd.ExecuteNonQuery();
}
This is considering the condition that the ddlfaculty dropdown
has the Value same as its Text.

Try this
if(ddlfaculty.selectedindex !=-1 )
{
do the insert function
}

Related

asp:gridview filter using listbox cannot make multiple selection

I have this asp:gridview in which I show data using mySql stored procedure. I have this listbox named ddlstatus which I use to filter the data. I use viewstate to show data that are selected from the listbox. The problem is I want to make multiple selection on this listbox and show data for each selection made on it, but when it only shows data for the initial selection.
The below is the client side code:
<asp:Label ID="lblstat" Text="status" Visible="false" runat="server"></asp:Label>
<asp:ListBox ID="ddlstatus" runat="server" OnSelectedIndexChanged="DropDownChange" AutoPostBack="true" AppendDataBoundItems="true" SelectionMode="Multiple"></asp:ListBox>
<asp:GridView ID="gdvTM" runat="server" ControlStyle-Width="100%" AutoGenerateColumns="False" DataKeyNames="ID" OnRowDeleting="gdvTM_RowDeleting" PageSize="5" CssClass="cssgridview" AlternatingRowStyle-BackColor="#d5d8dc">
<Columns >
<asp:TemplateField HeaderText="Current Status">
<ItemTemplate >
<asp:Label ID="lblcstat" runat="server" Text='<%# Eval("status") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The below is the server side code:
private void BindDropDownList()
{
PopulateDropDown(ddlstatus, lblstat.Text);
}
private void PopulateDropDown(ListBox ddl, string columnName)
{
ddl.Items.Clear();
ddl.DataSource = BindDropDown(columnName);
ddl.DataTextField = columnName;
ddl.DataValueField = columnName;
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("Please select", "0"));
}
private void BindGrid()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlDataAdapter sda = new MySqlDataAdapter();
MySqlCommand cmd = new MySqlCommand("GetTMData");
cmd.CommandType = CommandType.StoredProcedure;
string statusVal = null;
if (ViewState["stat"] != null && ViewState["stat"].ToString() != "0")
{
statusVal = ViewState["stat"].ToString();
}
cmd.Parameters.AddWithValue("statusVal", statusVal);
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
gdvTM.DataSource = dt;
int i = dt.Rows.Count;
gdvTM.DataBind();
this.BindDropDownList();
TableCell cell = gdvTM.HeaderRow.Cells[0];
setDropdownselectedItem(ViewState["stat"] != null ? (string)ViewState["stat"] : string.Empty, ddlstatus);
}
private void setDropdownselectedItem(string selectedvalue, ListBox ddl)
{
if (!string.IsNullOrEmpty(selectedvalue))
{
ddl.Items.FindByValue(selectedvalue).Selected = true;
}
}
protected void DropDownChange(object sender, EventArgs e)
{
ListBox dropdown = (ListBox)sender;
string selectedValue = dropdown.SelectedItem.Value;
switch (dropdown.ID.ToLower())
{
case "ddlstatus":
ViewState["stat"] = selectedValue;
break;
}
this.BindGrid();
}
private DataTable BindDropDown(string columnName)
{
string username = uName.Text;
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlCommand cmd = new MySqlCommand("SELECT DISTINCT (" + columnName + ") FROM approved WHERE tm = #tm AND " + columnName + " IS NOT NULL", con);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
cmd.Parameters.AddWithValue("#tm", username);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
Below is the MySql stored procedure:
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetTMData`(in statusVal varchar(45))
BEGIN
SELECT *
FROM approved
WHERE (statusVal IS NULL
OR status = statusVal)
order by date desc;
END
How can I make this happen? Thanks in advance.
Please make listbox multiple
<asp:ListBox id="ListBox1"
Rows="6"
Width="100px"
**SelectionMode="Multiple"**
runat="server">
<asp:ListItem Selected="True">Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
<asp:ListItem>Item 4</asp:ListItem>
<asp:ListItem>Item 5</asp:ListItem>
<asp:ListItem>Item 6</asp:ListItem>
</asp:ListBox>
Then in server side
void SubmitBtn_Click(Object sender, EventArgs e)
{
Message.Text = "You chose: <br />";
// Iterate through the Items collection of the ListBox and
// display the selected items.
foreach (ListItem item in ListBox1.Items)
{
if(item.Selected)
{
Message.Text += item.Text + "<br />";
}
}
}
First of all, auto post back not allow you to select multiple items because upto select second item, the postback already happens by first selected item so,
You have to set AutoPostBack="false" for your list box,
<asp:ListBox ID="ddlstatus" runat="server" AutoPostBack="false" AppendDataBoundItems="true" SelectionMode="Multiple"></asp:ListBox>
For collecting multiple selected items we simply choose button for instance, you can collect those items wherever you want,
Then add one button that will call below code
<asp:Button ID="button1" runat="server" OnClick="button1_Click" Text="Click"/>
On above button event handler add below code,
protected void button1_Click(object sender, EventArgs e)
{
var selectedNames = ddlstatus.Items.Cast<ListItem>()
.Where(i => i.Selected)
.Select(i => i.Value)
.ToList();
string selectedValue = string.Join("','", selectedNames);
selectedValue = "'" + selectedValue + "'";
ViewState["stat"] = selectedValue;
}
Then the comma separated items in your ViewState will be used in your stored procedure parameter
string statusVal = null;
if (ViewState["stat"] != null && ViewState["stat"].ToString() != "0")
{
statusVal = ViewState["stat"].ToString();
}
cmd.Parameters.AddWithValue("statusVal", statusVal); //<= Now this string variable contains comma separated list box items values.
If you populate your list box on Page_Load then make sure that you should populate it into !Page.IsPostBack like
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Populate your list box here
}
}
And your SP is
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetTMData1`(in statusVal varchar(255))
BEGIN
IF statusVal = '\'\'' THEN
select * from approved;
ELSE
SET #sql = CONCAT('SELECT * FROM approved WHERE status IN (', statusVal, ')');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF ;
END
If you select multiple items from the dropdown then your SP's parameter data look like '\'apple\',\'banana\''. If not then it look like '\''.
There's a few issues that I could spot that may need to be addressed,
Ensure that the method BindDropDownList is only called on a non postback (page refresh), because your method PopulateDropDown is clearing the items on the list which means that viewstate cannot be restored in a postback, hence the probable reason why only one item is being selected.
I'm not 100% of the table schema, but the SQL provided does not seem to be able to query by more than one status properly, you should probably send a comma separated list of values, and in SQL turn them into a temp table so that you effectively search for items with multiple status (you should probably create a new question for this).
Do not use SelectedItem for multiple selections, instead you need to iterate your list items for those that are selected, and you don't need to use ViewState to pass it along (you probably did because of point 1. above). For example you could replace your method BindGrid and DropDownChange with:
private void BindGrid()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlDataAdapter sda = new MySqlDataAdapter();
MySqlCommand cmd = new MySqlCommand("GetTMData");
cmd.CommandType = CommandType.StoredProcedure;
string statusVal = null;
foreach (ListItem item in ddlstatus.Items)
{
if(item.Selected)
{
if(statusVal.length > 0)
statusVal += ",";
statusVal += item.Value;
}
}
cmd.Parameters.AddWithValue("statusVal", statusVal);
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
gdvTM.DataSource = dt;
gdvTM.DataBind();
}
protected void DropDownChange(object sender, EventArgs e)
{
this.BindGrid();
}

dynamically add itemplate to the gridview

I have created gridview. Added a textbox to specify what number of columns user want to add to the grid dynamically and its done successfully.
I want to add text box to the dynamically added fields to enter the data and save it to the database(I am able to add text fields to the rows and save data) but i didnt got any solution yet.
I have tried with itemplate but I don't know much about it. i have added my code below.
Here is my aspx code
<input type="hidden" runat="server" value="0" id="columnAdded"/>
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<%--<asp:CommandField ShowEditButton="True" />--%>
<asp:TemplateField HeaderText="S. No.">
<ItemTemplate>
<asp:Label ID="lblsno" runat="server" Text='<%#Container.DataItemIndex+1 %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lbInsert" runat="server">Insert</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Parts" DataField="parts">
</asp:BoundField>
<%--<asp:TemplateField>
<ItemTemplate>
<asp:PlaceHolder ID="PlaceHolder_InputControl" runat="server" ></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>--%>
<%--<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnedit" runat="server" Text="Edit" CommandName="EditRow"/>
</ItemTemplate>
</asp:TemplateField>--%>
</Columns>
</asp:GridView>
and here is .cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
drpstation.Items.Clear();
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from stationdesc where stndesc <> '' and id is not null";
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds, "stationdesc");
drpstation.DataSource = ds.Tables[0];
drpstation.DataTextField = ds.Tables[0].Columns["stndesc"].ColumnName.ToString();
drpstation.DataValueField = ds.Tables[0].Columns["id"].ColumnName.ToString();
drpstation.DataBind();
drpstation.Items.Insert(0, new ListItem("Select Station", "0"));
}
catch (Exception ex)
{
string Msg = "select station error";
Msg += ex.Message;
}
finally
{
con.Close();
}
}
if (!IsPostBack)
{
griddisplay();
}
}
public void griddisplay()
{
try
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM stnparts", con);
SqlDataReader dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
//DataTable dt = new DataTable();
//dt.Columns.Add("Parts", typeof(string));
//DataRow drr = dt.NewRow();
//drr["Parts"] = "Weldmet";
//dt.Rows.Add(drr);
//drr = dt.NewRow();
//drr["Parts"] = "MFG Parts";
//dt.Rows.Add(drr);
//GridView1.DataSource = dt;
//GridView1.DataBind();
}
catch (Exception d)
{
string message = "grid error";
message += d.Message;
}
finally
{
con.Close();
}
}
protected void btnadd_Click(object sender, EventArgs e)
{
int num;
num = Convert.ToInt32(txtnumber.Text.Trim());
int addedColumn = Convert.ToInt32(columnAdded.Value);
for (int i = addedColumn + 1; i <= addedColumn + num; i++)
{
string name = "Unit";
name = string.Concat(name, i);
TemplateField test = new TemplateField();
test.HeaderText = name;
GridView1.Columns.Add(test);
TextBox txtname = new TextBox();
string txtunit = "txtunit";
txtname.ID = txtunit + i;
}
griddisplay();
columnAdded.Value = (addedColumn + num).ToString();
}
public class TemplateHandler : ITemplate
{
void ITemplate.InstantiateIn(Control container)
{
TextBox txtbox = new TextBox();
txtbox.Text = "test";
txtbox.DataBinding += Txtbox_Binding;
container.Controls.Add(txtbox);
}
private void Txtbox_Binding(object sender, EventArgs e)
{
//throw new NotImplementedException();
TextBox txttest = (TextBox)sender;
GridViewRow container = (GridViewRow)txttest.NamingContainer;
//txttest.Text = ((TableNameClass)container.DataItem).SkillText;
((DataRowView)container.DataItem)["SkillText"].ToString();
}
}
Please help
Just a pseudo/sample code(not tested!) based on the code you posted, to give you some heads-up
protected void btnadd_Click(object sender, EventArgs e)
{
int num;
num = Convert.ToInt32(txtnumber.Text.Trim());
int addedColumn = Convert.ToInt32(columnAdded.Value);
for (int i = addedColumn + 1; i <= addedColumn + num; i++)
{
string name = "Unit";
name = string.Concat(name, i);
TemplateField test = new TemplateField();
test.HeaderText = name;
test.ItemTemplate = new TemplateHandler (); // ** This line to set ItemTemplate is missing in the code you posted
GridView1.Columns.Add(test);
// ... Other code as you need
}
}
Hope this help you.

Give the gridview columns a alias name in C#

I have a GridView which is not DataSource bound. At run time this GridView shows some rows at run time. There is a requirement in which user should be able to change the column header text at run time. So i thought of to implement in this way -
User will double click [or single click] on column header and a text box will be visible to user, where user will enter the new text and as soon as user leaves the text box, new column header text will be set as HeaderText property of the column. Can this achieved? can anyone share the sample code to achieve the same? I will be highly obliged to you. Any help will be appreciable.
This is my grid
<asp:GridView ID="GdvTestData" runat="server"
class="table table-striped table-responsive table-hover"
onrowdatabound="gv_RowDataBound"
PageSize="100" OnSelectedIndexChanged="GdvTestData_SelectedIndexChanged">
<FooterStyle BorderStyle="Solid" />
</asp:GridView>
Here is the thing that you can do to bind alias with the column
Below is aspx code
<asp:DropDownList runat="server" ID="ddlQuery">
<asp:ListItem Text="Query1" Value="1" Selected="True"></asp:ListItem>
<asp:ListItem Text="Query2" Value="2"></asp:ListItem>
<asp:ListItem Text="Query3" Value="3"></asp:ListItem>
</asp:DropDownList>
<asp:TextBox runat="server" ID="txtAlias"></asp:TextBox>
<asp:Button runat="server" ID="btnGetData" Text="GetData" OnClick="btnGetData_Click" />
<asp:GridView runat="server" ID="gcData"></asp:GridView>
And code to bind data to grid in cs is below
protected void btnGetData_Click(object sender, EventArgs e)
{
GetData();
}
private void GetData()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Connection String";
string Query = string.Empty;
if (ddlQuery.SelectedValue == "1")
Query = "SELECT * FROM Table1";
else if (ddlQuery.SelectedValue == "2")
Query = "SELECT * FROM Table2";
else if (ddlQuery.SelectedValue == "3")
Query = "SELECT * FROM Table3";
try
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = Query;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
DataTable dtFinal = new DataTable();
foreach (DataColumn cln in dt.Columns)
{
dtFinal.Columns.Add(cln.ColumnName + " " + txtAlias.Text, cln.DataType);
}
foreach (DataRow row in dt.Rows)
{
DataRow dr = dtFinal.NewRow();
for (int i = 0; i < dtFinal.Columns.Count; i++)
{
dr[i] = row[i];
}
dtFinal.Rows.Add(dr);
}
gcData.DataSource = dtFinal;
gcData.DataBind();
}
catch (Exception)
{
throw;
}
}

Make ASP Validators validate just one gridview row?

I am making a little website for myself and within this website you can make users. The moment you add a user it goes into a database. You can also see the existing users in a gridview, so when you make a new user it goes into the gridview. But one little problem, when I try and use validators within this gridview, it validates every row. I need it to validate just one row. Someone said something about row ID, but i don't know how to make that work.
As you can see I've tried some stuff with RowIndex, but couldn' t get it to work
Any help is appreciated
Management.Aspx :
<asp:GridView runat="server" ID="gridUsers" AutoGenerateColumns="False" DataKeyNames="username" DataSourceID="DSUserList" OnRowCommand="gridUsers_RowCommand">
<Columns>
<asp:BoundField DataField="username" HeaderText="Gebruikersnaam" ReadOnly="True" SortExpression="username"></asp:BoundField>
<asp:BoundField DataField="display_name" HeaderText="Naam" SortExpression="display_name"></asp:BoundField>
<asp:TemplateField >
<ItemTemplate>
<asp:Button OnClientClick="ConfirmDeleteAdmin()" Text="Verwijderen" runat="server" id="btnDeleteUser" CommandName="delUser" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox runat="server" id="txtChangePassword" />
<%-- TODO: Mike: Validators via code --%>
<asp:Button OnClientClick="ConfirmChangePassword()" ValidationGroup="vgChangePW" Text="Wachtwoord wijzigen" runat="server" ID="btnChangePassword" CommandName="changePassword" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
<%-- <asp:RequiredFieldValidator ID="rfChangePassReq" ControlToValidate="<%# String.Format("txtChangePW{0}",((GridViewRow) Container).RowIndex).ToString() %>" ValidationGroup="vgChangePW" runat="server" ErrorMessage="<br/>U heeft geen nieuw wachtwoord ingevoerd"></asp:RequiredFieldValidator>--%>
<%-- asp:RegularExpressionValidator ID="rfChangePassReg" ValidationExpression="^(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$" ControlToValidate="<%# String.Format("txtChangePW{0}",((GridViewRow) Container).RowIndex).ToString() %>" ValidationGroup="vgChangePW" runat="server" ErrorMessage="<br/>Uw wachtwoord moet uit minimaal 6 tekenen bestaan en moet minimaal 1 hoofdletter en 1 cijfer bevatten"></asp:RegularExpressionValidator>--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Management.aspx.cs :
protected void btnCreateUser_Click(object sender, EventArgs e)
{
try {
connection.Open();
} catch (Exception) {}
String password = txtPassword.Text.Trim();
password = password != "" ? ProjectManager.GetSHA1HashData(password) : "";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = connection;
cmd.CommandText = "sp_add_user";
cmd.Parameters.Add("#username", SqlDbType.NVarChar, 100).Value = txtUsername.Text;
cmd.Parameters.Add("#password", SqlDbType.NVarChar, 100).Value = password;
cmd.Parameters.Add("#displayName", SqlDbType.NVarChar, 100).Value = txtDisplayName.Text;
cmd.Parameters.Add("#return_value", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
int code = int.Parse(cmd.Parameters["#return_value"].Value.ToString());
if (code == 0)
{
lblNewUserStatus.Text = "Gebruiker bestaat al";
lblNewUserStatus.ForeColor = Color.Red;
}
else
{
DSUserList.EnableCaching = false;
gridUsers.DataBind();
DSUserList.EnableCaching = true;
lblNewUserStatus.Text = "Gebruiker toegevoegd";
lblNewUserStatus.ForeColor = Color.Black;
txtUsername.Text = "";
txtPassword.Text = "";
txtDisplayName.Text = "";
}
connection.Close();
}
protected void gridUsers_RowCommand(object sender, GridViewCommandEventArgs e)
{
// Deletes user or changes a password of a user
if (e.CommandName == "delUser")
{
string confirmValue = Request.Form["delete_admin"];
if (confirmValue == "Yes") {
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gridUsers.Rows[index];
String usernameToDelete = row.Cells[0].Text;
try {
connection.Open();
} catch (Exception) { }
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = connection;
cmd.CommandText = "sp_delete_user";
cmd.Parameters.Add("#username", SqlDbType.NVarChar, 100).Value = usernameToDelete;
cmd.Parameters.Add("#return_value", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
int code = int.Parse(cmd.Parameters["#return_value"].Value.ToString());
if (code == 0) {
//Failed
lblDelteStatus.Text = "Kan gebruiker admin niet verwijderen";
lblDelteStatus.ForeColor = Color.Red;
} else {
// Deleted
lblDelteStatus.Text = "Gebruiker verwijderd";
lblDelteStatus.ForeColor = Color.Black;
// Reload user list
DSUserList.EnableCaching = false;
gridUsers.DataBind();
DSUserList.EnableCaching = true;
}
connection.Close();
if (usernameToDelete == Session["username"].ToString()) {
ProjectManager.logout();
Page.Response.Redirect(Page.Request.Url.ToString());
}
}
}
else if (e.CommandName == "changePassword")
{
string confirmValue = Request.Form["change_password"];
if (confirmValue == "Yes") {
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gridUsers.Rows[index];
String username = row.Cells[0].Text;
TextBox txtPassword = (TextBox)row.Cells[3].FindControl("txtChangePassword");
String password = txtPassword.Text.Trim();
password = password != "" ? ProjectManager.GetSHA1HashData(password) : "";
try {
connection.Open();
} catch (Exception) { }
cmd.Connection = connection;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_change_password";
cmd.Parameters.Add("#password", SqlDbType.NVarChar, 100).Value = password;
cmd.Parameters.Add("#username", SqlDbType.NVarChar, 100).Value = username;
cmd.Parameters.Add("#return_value", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
int code = int.Parse(cmd.Parameters["#return_value"].Value.ToString());
if (code == 0) {
lblDelteStatus.Text = "Dit wachtwoord is onlangs gebruikt, kies een ander wachtwoord";
lblDelteStatus.ForeColor = Color.Red;
} else if (code == 1) {
lblDelteStatus.Text = "Wachtwoord gewijzigd";
lblDelteStatus.ForeColor = Color.Black;
}
connection.Close();
}
}
}
Try this in the RowDataBound event:
Create a row specific validation group name that is a concatenation of some prefix and the row index and assign it to each validator and control in the row that is part of the validation group... i.e.:
valGroupName = string.format("vgRow{0}", e.row.rowindex.tostring);
Button btn = e.row.FindControl("btnChangePassword");
btn.ValidationGroup = valGroupName
RequiredFieldValidator vreq = e.row.FindControl("rfChangePassReq");
vreq.ValidationGroup = valGroupName
RegularExpressionValidator vregx = e.row.FindControl("rfChangePassReg");
vregx.ValidationGroup = valGroupName
...etc...
This way only validation for the specific row should be triggered when you select the row button to save.
I don't recall and I can't test it right now, but you may have an issue with any field that is connected to a RequiredFieldValidator, it may prevent posting. You'll have to check that out. You might be ok as they will be part of a different validation group.

Insert the data when user click on select button inside the gridview

I have a gridview as below
<asp:GridView ID="gvDoctorList" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
AllowPaging="True" AllowSorting="True"
OnSelectedIndexChanged="gvDoctorList_SelectedIndexChanged" OnRowCommand="gvDoctorList_RowCommand" OnRowDataBound="gvDoctorList_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%--<asp:CheckBox runat="server" ID="chk" OnCheckedChanged="chk_CheckedChanged" AutoPostBack="true" />--%>
<asp:Label runat="server" ID="lblPID" Visible="false" Text='<%# Eval("PatientId") %>'></asp:Label>
<asp:Button ID="btnSelect" runat="server" Text="Select" CommandArgument='<%# Eval("PatientId") %>' CommandName = "Select" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="PatientId" HeaderText="PatientId" SortExpression="PatientId" />
<asp:BoundField DataField="firstname" HeaderText="firstname" SortExpression="firstname" />
<asp:BoundField DataField="lastname" HeaderText="lastname" SortExpression="lastname" />
<asp:BoundField DataField="sex" HeaderText="sex" SortExpression="sex" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MyDatabaseConnectionString %>"
SelectCommand="SELECT [PatientId],[firstname], [lastname], [sex] FROM [PatientDetails]"></asp:SqlDataSource>
<asp:Button ID="btnformatric" runat="server" Text="formatric3d" OnClick="btnformatric_Click" />
Code behind gridview rowcommand is as below
protected void gvDoctorList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int pID = Convert.ToInt32(e.CommandArgument);
Session["PatientId"] = Convert.ToString(e.CommandArgument);
//Server.Transfer("Patientstaticformatrix.aspx");
string pIDstr = Convert.ToString(Session["PatientId"]);
if (!string.IsNullOrEmpty(pIDstr))
{
int patientID = Convert.ToInt32(pID);
//string connection = System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
string sqlquery = "SELECT * FROM [MyDatabase].[dbo].[PatExam] where PId = '" + patientID + "'";
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
using(SqlConnection conn = new SqlConnection(connection))
{
//SqlConnection conn = new SqlConnection(con);
DataSet ds;
ds = new DataSet();
SqlDataAdapter cmpatientexam;
conn.Open();
cmpatientexam = new SqlDataAdapter(sqlquery, conn);
cmpatientexam.Fill(ds, "PatientExam");
TreeNode pidnode = new TreeNode();
pidnode.Text = pIDstr;
foreach (DataRow patrow in ds.Tables["PatientExam"].Rows)
{
//TreeNode tvpatexam = new TreeNode();
//tvpatexam.Text = patrow["PId"].ToString();
//TreeView1.Nodes.Add(tvpatexam);
//for (int i = 0; i < ds.Tables["PatientExam"].Columns["PId"].Count; i++)
//if (patrow["PId"].ToString() != DBNull.Value)
//{
TreeNode childtvpatexam = new TreeNode();
childtvpatexam.Text = patrow["Exam"].ToString();
pidnode.ChildNodes.Add(childtvpatexam);
//break;
//}
//TreeView1.Nodes.Add(tvpatexam);
}
TreeView1.Nodes.Add(pidnode);
ds.Dispose();
cmpatientexam.Dispose();
conn.Close();
conn.Dispose();
}
}
}
}
Code behind the button click event is as below
protected void btnformatric_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gvDoctorList.Rows)
{
Button btn = (Button)row.FindControl("Select");
if (btn != null)
{
string pIDstr = Convert.ToString(Session["PatientId"]);
string exam = ((Button)sender).Text;
SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[PatExam]([PId],[Exam]) VALUES (#pid,#exam)", con);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
try
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#pid", pIDstr);
cmd.Parameters.AddWithValue("#exam", exam);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write("Error Occured: " + ex.Message.ToString());
}
finally
{
con.Close();
cmd.Dispose();
}
}
}
}
I want to insert the value which is selected from gridview using select button and insert that selected value on button click event....but with the above code it is not working...
Can anyone suggest me some other idea or if possible with these code then how...can you give me the code for it....Thanks a lot
You can add a hidden field and save Gridview's rowindex in the hidden field. In btnformatric_Click you can get the row by index and get the data. The markup:
<asp:HiddenField ID="hdnRowIndex" runat="server" Value ="" />
<asp:Button ID="btnformatric" runat="server" Text="formatric3d" OnClick="btnformatric_Click" />
In code, gvDoctorList_RowCommand method:
protected void gvDoctorList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int pID = Convert.ToInt32(e.CommandArgument);
Session["PatientId"] = Convert.ToString(e.CommandArgument);
//Server.Transfer("Patientstaticformatrix.aspx");
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
hdnRowIndex.Value = gvr.RowIndex.ToString();
... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
btnformatric_Click method:
protected void btnformatric_Click(object sender, EventArgs e)
{
int rowIndex = 0;
if (int.TryParse(hdnRowIndex.Value, out rowIndex))
{
//Get the row
GridViewRow row = gvDoctorList.Rows[rowIndex];
Button btn = (Button)row.FindControl("Select");
if (btn != null)
{
string pIDstr = Convert.ToString(Session["PatientId"]);
string exam = ((Button)sender).Text;
SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[PatExam]([PId],[Exam]) VALUES (#pid,#exam)", con);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
try
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#pid", pIDstr);
cmd.Parameters.AddWithValue("#exam", exam);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write("Error Occured: " + ex.Message.ToString());
}
finally
{
con.Close();
cmd.Dispose();
}
}
}
}
I presume that you're interested in inserting a record based on the selected PatientID value from the GridView?
What you want to do is start by setting the GridView's DataKeyNames property to PatientID like so:
<asp:GridView ID="gvDoctorList" runat="server" DataKeyNames="PatientID" ...>
Then in the btnformatric_Click event handler you can get the selected PatientID value via gvDoctorList.SelectedValue, as in:
string pIDstr = gvDoctorList.SelectedValue.ToString();
Of course, before you do the above you should check to make sure that the user has selected a patient from the grid (namely, that gvDoctorList.SelectedIndex >= 0).

Categories