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;
}
}
Related
I work on asp.net web forms with c# I need to add checkbox column as last column on gridview
but i don't know how to add it
static string con =
"Data Source=DESKTOP-L558MLK\\AHMEDSALAHSQL;" +
"Initial Catalog=UnionCoop;" +
"User id=sa;" +
"Password=321;";
SqlConnection conn = new SqlConnection(con);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridViewSearch.DataSource = GetDataForSearch();
GridViewSearch.DataBind();
}
}
public DataTable GetDataForSearch()
{
string response = string.Empty;
SqlCommand cmd = new SqlCommand();
DataTable dt = new DataTable();
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "select top 10 datelogged AS EntredDatetime, Doc_type AS OrderType, Printer_name, BranchID AS BranchCode, id from Print_Report";
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 50000;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
}
catch (Exception ex)
{
response = ex.Message;
}
finally
{
cmd.Dispose();
conn.Close();
}
return dt;
}
on aspx page
<asp:GridView ID="GridViewSearch" runat="server">
</asp:GridView>
GridViewSearch.DataSource = GetDataForSearch();
DataGridViewCheckBoxColumn checkColumn = new DataGridViewCheckBoxColumn();
checkColumn.Name = "X";
checkColumn.HeaderText = "X";
checkColumn.Width = 50;
checkColumn.ReadOnly = false;
checkColumn.FillWeight = 10; //if the datagridview is resized (on form resize) the checkbox won't take up too much; value is relative to the other columns' fill values
GridViewSearch.Columns.Add(checkColumn);
GridViewSearch.DataBind();
I get error on line below
GridViewSearch.Columns.Add(checkColumn);
argument 1 can't convert from system.windows.forms.datagridviewcheckbox to system.web.ui.webcontrol.databoundfield
so how to solve this issue please ?
Seems to me, that if you want say a button, or check box, or dropdown?
why not just add it to the markup.
So, say like this:
<div id="MyGridPick" runat="server" style="display:normal;width:40%">
<asp:Label ID="lblSel" runat="server" Text="" Font-Size="X-Large"></asp:Label>
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" cssclass="table table-hover" OnRowDataBound="GridView1_RowDataBound" >
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" ItemStyle-Width="120px" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkSel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
Then my code to load is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
SqlCommand cmdSQL =
new SqlCommand("SELECT * FROM tblHotelsA ORDER BY HotelName");
GridView1.DataSource = MyRstP(cmdSQL);
GridView1.DataBind();
}
Now, of course I get VERY tired of typing that connection string stuff over and over. So, I have a "genreal" routine like this:
public DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
cmdSQL.Connection = conn;
using (cmdSQL)
{
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
And the result of running above:
So, kind of hard to make the case to "add" a check box control, when you can just drop one into the gridview.
Same goes for a button, maybe we want a button to "view" or edit the above row, or some such.
So, once again, just drop in a plain jane button, say like this:
<asp:TemplateField HeaderText="View" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:Button ID="bView" runat="server" Text="View" CssClass="btn"
OnClick="bView_Click" />
</ItemTemplate>
</asp:TemplateField>
And now we have this:
And EVEN better?
Well, since that button (or check box) is a plain jane standard control?
then you can add standard events, like a click event, or whatever you want.
Say this code for the button click (shows how to get current row).
protected void bView_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow gRow = btn.NamingContainer as GridViewRow;
int PKID = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
SqlCommand cmdSQL =
new SqlCommand("SELECT * FROM tblHotelsA WHERE ID = #ID");
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID;
DataTable dtHotel = MyRstP(cmdSQL);
General.FLoader(MyEditArea, dtHotel.Rows[0]);
MyGridPick.Style.Add("display", "none"); // hide grid
MyEditArea.Style.Add("display", "normal"); // show edit div area
}
And we now get/see this:
Edit: Process each checked/selected row.
this:
protected void cmdSelProcess_Click(object sender, EventArgs e)
{
// process all rows in GV with check box
String sPK = "";
List<int> MySelected = new List<int>();
foreach (GridViewRow gRow in GridView1.Rows)
{
CheckBox chkSel = (CheckBox)gRow.FindControl("chkSel");
if (chkSel.Checked)
{
int PK = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
// add pk value of row to our list
MySelected.Add(PK);
// Or we could process data based on current gRow
if (sPK != "")
sPK += ",";
sPK += PK.ToString();
Debug.Print(PK.ToString());
}
}
// at this point, we have a nice list of selected in MySelected
// or, maybe process as a data table
SqlCommand cmdSQL =
new SqlCommand($"SELECT * FROM tblHotelsA where ID IN({sPK})");
DataTable rstSelected = MyRstP(cmdSQL);
//
foreach (DataRow dr in rstSelected.Rows)
{
// do whatever
}
}
Datagridviewcheckboxcolumn is a Windows formx object. You are working in web forms. Please see the link below for information on the webforms check box field
CheckBoxField checkColumn = new CheckBoxField();
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();
}
What i'm trying to do is execute some code when a checkbox in a gridview is checked, with the code being executed row by row. I debugged the code and every time returns false despite the checkboxes being checked. The code i'm trying to execute works if the conditional statement is removed.
protected void ShoppingCartButton_Click(object sender, EventArgs e)
{
Label1.Text = "HIH0HI";
OleDbConnection myconn = new OleDbConnection();
myconn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|ProjectDatabase.accdb";
string UserID = Session["UserID"].ToString();
StringBuilder sb3 = new StringBuilder();
foreach (GridViewRow row in GridView1.Rows)
{
string unpredictable = "";
bool hi = true;
unpredictable = row.Cells[1].Text;
CheckBox chk = row.Cells[0].Controls[1] as CheckBox;
hi = chk.Checked;
sb3.Append(hi.ToString());
if (hi==true)
{
string command1 = "insert into Cart ([Username],[GameID]) values (#Username, #GameID)";
OleDbCommand cmd = new OleDbCommand(command1, myconn);
cmd.Parameters.AddWithValue("#Username", UserID);
cmd.Parameters.AddWithValue("#GameID", unpredictable);
myconn.Open();
cmd.ExecuteNonQuery();
myconn.Close();
}
}
Label1.Text = sb3.ToString();
}
Markup for the button and the gridview
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True" EmptyDataText ="Data Entry Error">
<Columns>
<asp:TemplateField HeaderText ="Add to Cart?">
<ItemTemplate>
<asp:CheckBox ID="checkbx" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button runat="server" id="ShoppingCartButton" Text="Add to shopping cart" OnClick="ShoppingCartButton_Click" />
This was a simple one. Have to enclose any data binding logic in
if (!IsPostBack)
this is eswar.k , i have one problem in asp.net..that is ..
i have one datalist .that is shows data from database ..that is contains .check box,image,and lables..here what is the problem .. when i am checked on check box ,i have to display the email labels into the text box..(like multiple recipients eg:eswar#gmil.com,eee#yahoo.in..etc )
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string strconnstring = System.Configuration.ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString;
string strquery = "select chid,chname,chlanguage,chrating,chemail,contenttype,data from tbl_channel_join Order by chid";
SqlCommand cmd = new SqlCommand(strquery);
SqlConnection con = new SqlConnection(strconnstring);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
//GridView1.DataSource = dt;
//GridView1.DataBind();
//GridView2.DataSource = dt;
//GridView2.DataBind();
dl_channels.DataSource = dt;
dl_channels.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
dt.Dispose();
}
Let's say you have a Gridview with checkbox like this :
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="checkIT" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
<asp:Button ID="btnDisplay" runat="server" Text="Show data selected" OnClick="btnDisplay_Click"/>
<asp:TextBox id="textboxDataDisplay" runat="server" />
with a button to show the selected checkbox columns
C# code
protected void btnDisplay_Click(object sender, EventArgs e)
{
string data = "";
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkCtrl") as CheckBox);
if (chkRow.Checked)
{
string yourFirstRowCell = row.Cells[1].Text;
string yourSecondRowCell = row.Cells[2].Text;
string yourThirdRowCell = row.Cells[3].Text;
data = yourFirstRowCell + yourSecondRowCell + yourThirdRowCell;
}
}
}
textboxDataDisplay.text = data;
}
Row cells are the cells in that row you want to get where the checkbox is checked.
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
}