DataGrid Functionalities

19/04/2012 16:40

 

<asp:DataGrid ID="DataGrid1" runat="server" AutoGenerateColumns="False" CellSpacing="0"
                                                GridLines="none" AllowPaging="True" PageSize="10" OnCancelCommand="DataGrid1_CancelCommand"
                                                OnDeleteCommand="DataGrid1_DeleteCommand" OnEditCommand="DataGrid1_EditCommand"
                                                OnPageIndexChanged="DataGrid1_PageIndexChanged" OnUpdateCommand="DataGrid1_UpdateCommand"
                                                OnItemCommand="DataGrid1_ItemCommand" Visible="false" Width="100%" CssClass="Grid"
                                                OnItemDataBound="DataGrid1_ItemDataBound">
                                                <Columns>
                                                    <asp:BoundColumn DataField="Question_id" HeaderText="QuestionID" ReadOnly="True"
                                                        Visible="false"></asp:BoundColumn>
                                                    <asp:TemplateColumn HeaderText="Questions" HeaderStyle-Width="750px" HeaderStyle-HorizontalAlign="Center">
                                                        <ItemTemplate>
                                                            <table width="100%" cellpadding="0" cellspacing="0" style="text-align: left">
                                                                <tr>
                                                                    <td align="right" height="30px" bgcolor="#d5d3d0">
                                                                        <table cellpadding="0" cellspacing="0" width="40%">
                                                                            <tr>
                                                                                <td>
                                                                                    Marks:
                                                                                    <asp:Label ID="Label2" runat="server" Text='<%# Eval("Marks") %>'></asp:Label>
                                                                                </td>
                                                                                <td>
                                                                                    Seconds:
                                                                                    <asp:Label ID="lblSecond" runat="server" Text='<%# Eval("Seconds") %>'></asp:Label>
                                                                                </td>
                                                                                <td>
                                                                                    <asp:LinkButton ID="lnkEdit" runat="server" CssClass="edit_icon" CausesValidation="false"
                                                                                        CommandName="Edit"></asp:LinkButton>
                                                                                </td>
                                                                                <td>
                                                                                    <asp:LinkButton ID="btnDelete" runat="server" CssClass="cancel_icon" OnClientClick="return confirm('Are you sure you want to delete?');"
                                                                                        CommandName="Delete" CausesValidation="false" />
                                                                                </td>
                                                                            </tr>
                                                                        </table>
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td align="left">
                                                                        <table width="98%" cellpadding="0" cellspacing="0">
                                                                            <tr>
                                                                                <td height="10px" colspan="2">
                                                                                </td>
                                                                            </tr>
                                                                            <tr>
                                                                                <td>
                                                                                    <asp:Image ID="Img1" runat="server" CssClass="Image" src='<%# "ShowImage.ashx?imgid=" + Eval("Question_id")  %>' />
                                                                                </td>
                                                                                <td>
                                                                                    <asp:LinkButton ID="Link1" runat="server" Text='<%# StripHTML(Eval("Question_desc")) %>'
                                                                                        CommandArgument="GetAnswer" CausesValidation="false" CssClass="GridPop" />
                                                                                </td>
                                                                            </tr>
                                                                            <tr>
                                                                                <td height="10px" colspan="2">
                                                                                </td>
                                                                            </tr>
                                                                        </table>
                                                                    </td>
                                                                </tr>
                                                            </table>
                                                        </ItemTemplate>
                                                        <EditItemTemplate>
                                                            <table width="100%" cellpadding="0" cellspacing="0" style="text-align: left">
                                                                <tr>
                                                                    <td height="30px" bgcolor="#d5d3d0">
                                                                        <table cellpadding="0" cellspacing="0" width="100%">
                                                                            <tr>
                                                                                <td width="120px" align="left">
                                                                                    <table cellpadding="0" cellspacing="0" width="100%">
                                                                                        <tr>
                                                                                            <td>
                                                                                                <asp:LinkButton ID="lnkChangeImage" runat="server" CssClass="g_update" CausesValidation="false"
                                                                                                    Text="Change" CommandArgument="ChangeImage"></asp:LinkButton>
                                                                                            </td>
                                                                                            <td>
                                                                                                <asp:LinkButton ID="lnkRemoveImage" runat="server" CssClass="g_update" CausesValidation="false"
                                                                                                    CommandArgument="RemoveImage" Text="Remove" OnClientClick="return confirm('Are you sure you want to delete Image?');"></asp:LinkButton>
                                                                                            </td>
                                                                                        </tr>
                                                                                    </table>
                                                                                </td>
                                                                                <td align="right">
                                                                                    <table cellpadding="0" cellspacing="0" width="50%">
                                                                                        <tr>
                                                                                            <td>
                                                                                                Marks:
                                                                                                <asp:TextBox ID="txtmarks" runat="server" CssClass="NumberText" Text='<%# Eval("Marks") %>'></asp:TextBox>
                                                                                                <asp:RequiredFieldValidator ID="rqi" runat="server" ControlToValidate="txtmarks"
                                                                                                    Display="Dynamic" ErrorMessage="Enter the marks" CssClass="err"></asp:RequiredFieldValidator>
                                                                                                <asp:FilteredTextBoxExtender ID="ftxtmarks" runat="server" Enabled="True" FilterMode="ValidChars"
                                                                                                    FilterType="Numbers" TargetControlID="txtmarks" />
                                                                                            </td>
                                                                                            <td>
                                                                                                Seconds:
                                                                                                <asp:TextBox ID="txtSecond" runat="server" CssClass="NumberText" Text='<%# Eval("Seconds") %>'></asp:TextBox>
                                                                                                <asp:RequiredFieldValidator ID="rqiSec" runat="server" ControlToValidate="txtSecond"
                                                                                                    Display="Dynamic" ErrorMessage="enter the seconds" CssClass="err"></asp:RequiredFieldValidator>
                                                                                                <asp:FilteredTextBoxExtender ID="ftxtsec" runat="server" Enabled="True" FilterMode="ValidChars"
                                                                                                    FilterType="Numbers" TargetControlID="txtSeconds" />
                                                                                            </td>
                                                                                            <td height="35px">
                                                                                                <asp:LinkButton ID="lnkUpdate" runat="server" CssClass="g_update" Text="Update" CommandName="update"
                                                                                                    CausesValidation="false"></asp:LinkButton>
                                                                                            </td>
                                                                                            <td>
                                                                                                <asp:LinkButton ID="lnkcanc" runat="server" CssClass="g_update" Text="Cancel" CausesValidation="false"
                                                                                                    CommandName="cancel"></asp:LinkButton>
                                                                                            </td>
                                                                                        </tr>
                                                                                    </table>
                                                                                </td>
                                                                            </tr>
                                                                        </table>
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td>
                                                                        <table cellpadding="0" cellspacing="0" width="97%">
                                                                            <tr>
                                                                                <td>
                                                                                    <asp:Image ID="Img2" runat="server" CssClass="Image" src='<%# "ShowImage.ashx?imgid=" +Eval("Question_id")  %>' />
                                                                                </td>
                                                                                <td width="100%">
                                                                                    <asp:TextBox ID="txtques" runat="server" TextMode="MultiLine" CssClass="MultiText"
                                                                                        Text='<%# StripHTML(Eval("Question_desc")) %>'></asp:TextBox>
                                                                                    <asp:RequiredFieldValidator ID="rqi1" runat="server" ControlToValidate="txtques"
                                                                                        Display="Dynamic" ErrorMessage="Enter the question" CssClass="err"></asp:RequiredFieldValidator>
                                                                                </td>
                                                                            </tr>
                                                                        </table>
                                                                    </td>
                                                                </tr>
                                                            </table>
                                                        </EditItemTemplate>
                                                    </asp:TemplateColumn>
                                                </Columns>
                                                <EditItemStyle CssClass="GridCenter" />
                                                <HeaderStyle CssClass="GridHeader"></HeaderStyle>
                                                <ItemStyle CssClass="GridItem"></ItemStyle>
                                                <%--<AlternatingItemStyle CssClass="GridAltItem"></AlternatingItemStyle>--%>
                                                <PagerStyle CssClass="GridPager" HorizontalAlign="Right" Mode="NumericPages" />
                                            </asp:DataGrid>
 
 
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Collections;
using System.Globalization;
using System.Text.RegularExpressions;
 
namespace EmpRecuit
{
    public partial class Question : System.Web.UI.Page
    {
        DBConnect objDB = new DBConnect();
        SqlConnection clientcon = new SqlConnection();
        SqlCommand cmd;
 
        static int flg = 0;
 
        string ClientConnect;
        int Custid;
        string custName;
 
        int questId;
        private static string text;
        private static int qid;
 
        protected void Page_Load(object sender, EventArgs e)
        {
 
            custName = Menu.CustName;
            lblUserName.Text = custName;
            ClientConnect = Menu.ClientConnect;
            Custid = Menu.Custid;
 
            Label3.Text = "";
 
            if (!IsPostBack)
            {
                FillDropDown();
                ddlQuestionType.SelectedIndex = 0;
            }
 
 
        }
 
        void FillDropDown()
        {
            string SQLString = "SELECT * FROM Subject WHERE Cust_id=" + Custid + " ORDER BY Subject_id DESC ";
 
            DropDownList1.DataSource = objDB.getClientDataSet(SQLString, ClientConnect);
            DropDownList1.DataValueField = "Subject_id";
            DropDownList1.DataTextField = "Subject_name";
            DropDownList1.DataBind();
            DropDownList1.Items.Insert(0, "Select Subject");
        }
 
        public string StripHTML(object source)
        {
            try
            {
                string result;
 
                // Remove HTML Development formatting
                // Replace line breaks with space
                // because browsers inserts space
                result = (source).ToString().Replace("\r", " ");
                // Replace line breaks with space
                // because browsers inserts space
                result = result.Replace("\n", " ");
                // Remove step-formatting
                result = result.Replace("\t", string.Empty);
                // Remove repeating spaces because browsers ignore them
                result = System.Text.RegularExpressions.Regex.Replace(result,
                                                                      @"( )+", " ");
 
                // Remove the header (prepare first by clearing attributes)
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*head([^>])*>", "<head>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"(<( )*(/)( )*head( )*>)", "</head>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(<head>).*(</head>)", string.Empty,
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
 
                // remove all scripts (prepare first by clearing attributes)
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*script([^>])*>", "<script>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"(<( )*(/)( )*script( )*>)", "</script>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                //result = System.Text.RegularExpressions.Regex.Replace(result,
                //         @"(<script>)([^(<script>\.</script>)])*(</script>)",
                //         string.Empty,
                //         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"(<script>).*(</script>)", string.Empty,
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
 
                // remove all styles (prepare first by clearing attributes)
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*style([^>])*>", "<style>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"(<( )*(/)( )*style( )*>)", "</style>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(<style>).*(</style>)", string.Empty,
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
 
                // insert tabs in spaces of <td> tags
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*td([^>])*>", "\t",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
 
                // insert line breaks in places of <BR> and <LI> tags
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*br( )*>", "\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*li( )*>", "\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
 
                // insert line paragraphs (double line breaks) in place
                // if <P>, <DIV> and <TR> tags
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*div([^>])*>", "\r\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*tr([^>])*>", "\r\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*p([^>])*>", "\r\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
 
                // Remove remaining tags like <a>, links, images,
                // comments etc - anything that's enclosed inside < >
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<[^>]*>", string.Empty,
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
 
                // replace special characters:
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @" ", " ",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
 
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&bull;", " * ",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&lsaquo;", "<",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&rsaquo;", ">",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&trade;", "(tm)",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&frasl;", "/",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&lt;", "<",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&gt;", ">",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&copy;", "(c)",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&reg;", "(r)",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                // Remove all others. More can be added, see
                // https://hotwired.lycos.com/webmonkey/reference/special_characters/
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&(.{2,6});", string.Empty,
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
 
                // for testing
                //System.Text.RegularExpressions.Regex.Replace(result,
                //       this.txtRegex.Text,string.Empty,
                //       System.Text.RegularExpressions.RegexOptions.IgnoreCase);
 
                // make line breaking consistent
                result = result.Replace("\n", "\r");
 
                // Remove extra line breaks and tabs:
                // replace over 2 breaks with 2 and over 4 tabs with 4.
                // Prepare first to remove any whitespaces in between
                // the escaped characters and remove redundant tabs in between line breaks
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\r)( )+(\r)", "\r\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\t)( )+(\t)", "\t\t",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\t)( )+(\r)", "\t\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\r)( )+(\t)", "\r\t",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                // Remove redundant tabs
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\r)(\t)+(\r)", "\r\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                // Remove multiple tabs following a line break with just one tab
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\r)(\t)+", "\r\t",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                // Initial replacement target string for line breaks
                string breaks = "\r\r\r";
                // Initial replacement target string for tabs
                string tabs = "\t\t\t\t\t";
                for (int index = 0; index < result.Length; index++)
                {
                    result = result.Replace(breaks, "\r\r");
                    result = result.Replace(tabs, "\t\t\t\t");
                    breaks = breaks + "\r";
                    tabs = tabs + "\t";
                }
 
                // That's it.
                return result;
            }
            catch
            {
                //MessageBox.Show("Error");
                return source.ToString();
            }
        }
 
 
        protected void DataGrid1_EditCommand(object source, DataGridCommandEventArgs e)
        {
            DataGrid1.EditItemIndex = e.Item.ItemIndex;
            Binddata();
        }
 
        protected void DataGrid1_CancelCommand(object source, DataGridCommandEventArgs e)
        {
            DataGrid1.EditItemIndex = -1;
            Binddata();
        }
 
        protected void DataGrid1_UpdateCommand(object source, DataGridCommandEventArgs e)
        {
            string ques;
            int mark;
            int seconds;
            TextBox tb;
            string id;
 
            id = e.Item.Cells[0].Text;
 
            tb = (TextBox)e.Item.FindControl("txtques");
            ques = tb.Text;
 
            tb = (TextBox)e.Item.FindControl("txtmarks");
            mark = Convert.ToInt32(tb.Text);
 
            tb = (TextBox)e.Item.FindControl("txtSecond");
            seconds = Convert.ToInt32(tb.Text);
 
            try
            {
                clientcon = objDB.getClientConnection(ClientConnect);
                cmd = new SqlCommand("SP_UpdateQuestion", clientcon);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@QuestionDesc", SqlDbType.VarChar).Value = Server.HtmlEncode(ques);
                cmd.Parameters.Add("@Marks", SqlDbType.Int).Value = mark;
                cmd.Parameters.Add("@Seconds", SqlDbType.Int).Value = seconds;
                cmd.Parameters.Add("@QuestionId", SqlDbType.Int).Value = Convert.ToInt32(id);
                cmd.ExecuteScalar();
 
                cmd.Dispose();
                clientcon.Dispose();
                clientcon.Close();
            }
            catch { }
 
            DataGrid1.EditItemIndex = -1;
            Binddata();
 
        }
 
        protected void DataGrid1_DeleteCommand(object source, DataGridCommandEventArgs e)
        {
            string id;
            id = e.Item.Cells[0].Text;
 
            try
            {
                clientcon = objDB.getClientConnection(ClientConnect);
                cmd = new SqlCommand("DELETE FROM Question WHERE Question_id = @QuestionId", clientcon);
                cmd.Parameters.Add("@QuestionId", SqlDbType.Int).Value = Convert.ToInt32(id);
                cmd.ExecuteScalar();
 
                cmd.Dispose();
                clientcon.Dispose();
                clientcon.Close();
            }
            catch { }
 
            DataGrid1.EditItemIndex = -1;
            Binddata();
 
        }
        protected void Binddata()
        {
            try
            {
                int subjId = int.Parse(DropDownList1.SelectedItem.Value);
                string SQLString1 = "SELECT Question_id,Question_desc,Marks,Seconds FROM Question WHERE Subject_id =" + subjId + "  ORDER BY Question_id DESC";
                DataGrid1.DataSource = objDB.getClientDataSet(SQLString1, ClientConnect);
                DataGrid1.DataBind();
                ShowHideDatagridQuest();
            }
            catch { }
 
 
        }
 
 
        protected void DataGrid1_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
        {
            DataGrid1.CurrentPageIndex = e.NewPageIndex;
            Binddata();
 
        }
 
 
 
        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (DropDownList1.SelectedIndex == 0)
            {
                DataGrid1.Visible = false;
            }
            else
            {
                DataGrid1.Visible = true;
                Binddata();
 
            }
        }
 
        void ShowHideDatagridQuest()
        {
            if (DataGrid1.Items.Count == 0)
            {
                DataGrid1.Visible = false;
            }
            else
                DataGrid1.Visible = true;
        }
 
 
 
        protected void lnkSave_Click(object sender, EventArgs e)
        {
            try
            {
                clientcon = objDB.getClientConnection(ClientConnect);
                SqlCommand cmd;
                cmd = new SqlCommand("INSERT INTO Question(Subject_id,Question_desc,Marks,Seconds) VALUES(@SubjectId,@QuestionName,@Marks,@Seconds) SELECT @@IDENTITY", clientcon);
 
                string question = Server.HtmlEncode(txtquestion.Text);
 
                cmd.Parameters.Add("@SubjectId", SqlDbType.Int).Value = DropDownList1.SelectedItem.Value;
                cmd.Parameters.Add("@QuestionName", SqlDbType.VarChar).Value = question;
                cmd.Parameters.Add("@Marks", SqlDbType.Int).Value = Convert.ToInt32(txtmark.Text);
                cmd.Parameters.Add("@Seconds", SqlDbType.Int).Value = Convert.ToInt32(txtSeconds.Text);
 
 
                questId = int.Parse(cmd.ExecuteScalar().ToString());
                cmd.Dispose();
                clientcon.Dispose();
                clientcon.Close();
 
                //If image Question then
 
                if (ddlQuestionType.SelectedIndex == 2)
                {
                    ImageUpload();
                }
 
 
 
                DataGrid1.EditItemIndex = -1;
                Binddata();
 
                txtmark.Text = string.Empty;
                txtquestion.Text = string.Empty;
                txtSeconds.Text = string.Empty;
            }
            catch
            {
                Label3.Text = "Error: Cannot Insert";
            }
 
 
        }
 
        protected void lnkCancel_Click(object sender, EventArgs e)
        {
            //txtmark.Text = string.Empty;
            //txtquestion.Text = string.Empty;
 
            Response.Redirect("Menu.aspx?Cust_id=" + Custid + "&custName=" + custName + "");
        }
 
 
        protected void BindAnsGrid()
        {
            try
            {
                string SQL = "SELECT AnswerChoice,Correct_ans FROM Answer WHERE Question_id = " + Convert.ToInt32(ViewState["id"]) + " ";
                DataGrid2.DataSource = objDB.getClientDataSet(SQL, ClientConnect);
 
                DataGrid2.DataBind();
                ShowDatagridAns();
            }
            catch { }
        }
 
        protected void DataGrid1_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            try
            {
                ViewState["id"] = int.Parse(e.Item.Cells[0].Text);
 
                if (e.CommandArgument.ToString() == "GetAnswer")
                {
                    string quest;
                    LinkButton lnkquest;
 
                    BindAnsGrid();
 
                    lnkquest = (LinkButton)e.Item.FindControl("Link1");
                    quest = lnkquest.Text;
 
                    lblQuestion.Text = quest;
                    lblHeading.Text = "Answer";
 
                    pnlPop.Visible = true;
                    upnlAnswer.Visible = true;
                    upnlUpload.Visible = false;
                    Modalpopupextender1.Show();
                   
 
                    if (DataGrid2.Items.Count == 0)
                    {
                        DataGrid2.ShowHeader = false;
                    }
                    else
                        DataGrid2.ShowHeader = true;
 
                }
 
                if (e.CommandArgument.ToString() == "RemoveImage")
                {
                    string id;
                    id = e.Item.Cells[0].Text;
 
                    try
                    {
                        clientcon = objDB.getClientConnection(ClientConnect);
                        cmd = new SqlCommand("DELETE FROM [ImageQuestion] WHERE Question_id = @QuestionId", clientcon);
                        cmd.Parameters.Add("@QuestionId", SqlDbType.Int).Value = Convert.ToInt32(id);
                        cmd.ExecuteScalar();
 
                        cmd.Dispose();
                        clientcon.Dispose();
                        clientcon.Close();
                    }
                    catch { }
 
                    Binddata();
                   
 
                }
 
 
                if (e.CommandArgument.ToString() == "ChangeImage")
                {
                    string id;
                    id = e.Item.Cells[0].Text;
                    qid = int.Parse(id);
 
                    if (e.Item.ItemType == ListItemType.EditItem)
                    {
 
                        LinkButton lnkChange = (LinkButton)e.Item.FindControl("lnkChangeImage");
                        text = lnkChange.Text;
 
                    }
 
                    lblHeading.Text = "Upload Image";
                    pnlPop.Visible = true;
                    upnlAnswer.Visible = false;
                    upnlUpload.Visible = true;
                    Modalpopupextender1.Show();
 
                }
 
            }
            catch { }
 
        }
 
        void ShowDatagridAns()
        {
            if (DataGrid2.Items.Count == 0)
            {
                DataGrid2.Visible = false;
                DataGrid2.ShowHeader = false;
            }
            else
            {
                DataGrid2.Visible = true;
                DataGrid2.ShowHeader = true; ;
            }
        }
 
        protected void btnAdd_Click(object sender, EventArgs e)
        {
 
            try
            {
                if (flg == 0 && txtChoice.Text.Trim() != string.Empty)
                {
                    clientcon = objDB.getClientConnection(ClientConnect);
 
                    string answer = Server.HtmlEncode(txtChoice.Text);
                    cmd = new SqlCommand("SP_INSERTANSWER", clientcon);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@ansquesid", SqlDbType.Int).Value = Convert.ToInt32(ViewState["id"]);
                    cmd.Parameters.Add("@anschoice", SqlDbType.VarChar).Value = answer;
 
                    if (Correctanswer.Checked)
                        cmd.Parameters.Add("@correct", SqlDbType.Bit).Value = 1;
                    else
                        cmd.Parameters.Add("@correct", SqlDbType.Bit).Value = 0;
 
                    cmd.ExecuteNonQuery();
 
                    cmd.Dispose();
                    clientcon.Dispose();
                    clientcon.Close();
 
                    Label7.Text = string.Empty;
                }
                else
                    flg = 0;
            }
            catch { }
 
 
            DataGrid2.EditItemIndex = -1;
            BindAnsGrid();
 
            txtChoice.Text = string.Empty;
            Correctanswer.Checked = false;
 
 
        }
 
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            txtChoice.Text = string.Empty;
 
            pnlPop.Visible = false;
            Modalpopupextender1.Hide();
        }
 
        protected void DataGrid2_DeleteCommand(object source, DataGridCommandEventArgs e)
        {
 
            string choice;
 
            Label lblchoice = (Label)(e.Item.FindControl("lblchoice"));
            choice = Server.HtmlEncode(lblchoice.Text);
 
            try
            {
                clientcon = objDB.getClientConnection(ClientConnect);
 
                cmd = new SqlCommand("DELETE FROM Answer WHERE Question_id = @ansquesid AND AnswerChoice = @anschoice ", clientcon);
                cmd.Parameters.Add("@ansquesid", SqlDbType.Int).Value = Convert.ToInt32(ViewState["id"]);
                cmd.Parameters.Add("@anschoice", SqlDbType.VarChar).Value = choice;
                cmd.ExecuteScalar();
 
                cmd.Dispose();
                clientcon.Dispose();
                clientcon.Close();
            }
            catch { }
 
            DataGrid2.EditItemIndex = -1;
            BindAnsGrid();
        }
 
        protected void lnkClose_Click(object sender, EventArgs e)
        {
            pnlPop.Visible = false;
            Modalpopupextender1.Hide();
        }
 
        protected void Correctanswer_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                clientcon = objDB.getClientConnection(ClientConnect);
 
                cmd = new SqlCommand("SELECT COUNT(*) FROM Answer WHERE Question_id=" + Convert.ToInt32(ViewState["id"]) + " and Correct_ans=1 ", clientcon);
                int count = int.Parse(cmd.ExecuteScalar().ToString());
 
                cmd.Dispose();
                clientcon.Dispose();
                clientcon.Close();
 
                if (count == 0)
                {
                    Correctanswer.Checked = true;
                }
                else
                {
                    Correctanswer.Checked = false;
                    Label7.Text = "Correct Answer Already Selected";
                    flg = 1;
                }
            }
            catch { }
        }
 
 
        protected void lnkMainManu_Click(object sender, EventArgs e)
        {
            Response.Redirect("Menu.aspx?Cust_id=" + Custid + "&custName=" + custName + "");
        }
 
        protected void lnkLogout_Click(object sender, EventArgs e)
        {
            Response.Redirect("UserLogin.aspx");
        }
 
        public void ImageUpload()
        {
            try
            {
                FileUpload img = (FileUpload)ImgUploadQuestion;
                Byte[] imgByte = null;
                if (img.HasFile && img.PostedFile != null)
                {
                    //To create a PostedFile
                    HttpPostedFile File = ImgUploadQuestion.PostedFile;
                    //Create byte Array with file len
                    imgByte = new Byte[File.ContentLength];
                    //force the control to load data in array
                    File.InputStream.Read(imgByte, 0, File.ContentLength);
                }
                // Insert the employee name and image into db
                clientcon = objDB.getClientConnection(ClientConnect);
 
                string sql = "INSERT INTO ImageQuestion(Subject_id,Question_id,IMG_Question) VALUES(@Subject_id,@Question_id, @IMG_Question)";
                SqlCommand cmd = new SqlCommand(sql, clientcon);
 
                int subjetId = int.Parse(DropDownList1.SelectedValue.ToString());
                cmd.Parameters.AddWithValue("@Subject_id", subjetId);
                cmd.Parameters.AddWithValue("@Question_id", questId);
                cmd.Parameters.AddWithValue("@IMG_Question", imgByte);
                cmd.ExecuteScalar();
 
                cmd.Dispose();
 
                //lblResult.Text = String.Format("Employee ID is {0}", id);
            }
            catch
            {
                //lblResult.Text = "There was an error";
            }
            finally
            {
                clientcon.Close();
            }
 
        }
 
        public void ImageUpload_pop(int questionId)
        {
            try
            {
                FileUpload img = (FileUpload)uploadImage;
                Byte[] imgByte = null;
                if (img.HasFile && img.PostedFile != null)
                {
                    //To create a PostedFile
                    HttpPostedFile File = uploadImage.PostedFile;
                    //Create byte Array with file len
                    imgByte = new Byte[File.ContentLength];
                    //force the control to load data in array
                    File.InputStream.Read(imgByte, 0, File.ContentLength);
                }
                // Insert the employee name and image into db
                clientcon = objDB.getClientConnection(ClientConnect);
 
                string sql = "UPDATE ImageQuestion SET IMG_Question=@IMG_Question WHERE Question_id=@Question_id";
                SqlCommand cmd = new SqlCommand(sql, clientcon);
 
                cmd.Parameters.AddWithValue("@Question_id", questionId);
                cmd.Parameters.AddWithValue("@IMG_Question", imgByte);
                cmd.ExecuteNonQuery();
 
                cmd.Dispose();
 
                //lblResult.Text = String.Format("Employee ID is {0}", id);
            }
            catch
            {
                //lblResult.Text = "There was an error";
            }
            finally
            {
                clientcon.Close();
            }
 
        }
 
        public void ImageUpload_pop()
        {
            try
            {
                FileUpload img = (FileUpload)uploadImage;
                Byte[] imgByte = null;
                if (img.HasFile && img.PostedFile != null)
                {
                    //To create a PostedFile
                    HttpPostedFile File = uploadImage.PostedFile;
                    //Create byte Array with file len
                    imgByte = new Byte[File.ContentLength];
                    //force the control to load data in array
                    File.InputStream.Read(imgByte, 0, File.ContentLength);
                }
                // Insert the employee name and image into db
                clientcon = objDB.getClientConnection(ClientConnect);
 
                string sql1 = "SELECT Subject_Id FROM Question WHERE Question_id=" + qid + "";
                SqlCommand cmd1 = new SqlCommand(sql1, clientcon);
                int subId = int.Parse(cmd1.ExecuteScalar().ToString());
                cmd1.Dispose();
 
 
                string sql = "INSERT INTO ImageQuestion(Subject_id,Question_id,IMG_Question) VALUES(@Subject_id,@Question_id, @IMG_Question)";
                SqlCommand cmd = new SqlCommand(sql, clientcon);
                cmd.Parameters.AddWithValue("@Subject_id", subId);
                cmd.Parameters.AddWithValue("@Question_id", qid);
                cmd.Parameters.AddWithValue("@IMG_Question", imgByte);
                cmd.ExecuteScalar();
 
                cmd.Dispose();
 
                //lblResult.Text = String.Format("Employee ID is {0}", id);
            }
            catch
            {
                //lblResult.Text = "There was an error";
            }
            finally
            {
                clientcon.Close();
            }
 
        }
 
        protected void ddlQuestionType_SelectedIndexChanged(object sender, EventArgs e)
        {
 
            if (ddlQuestionType.SelectedIndex == 2)
            {
                ImgUploadQuestion.Visible = true;
                lblupload.Visible = true;
 
            }
            else
            {
                ImgUploadQuestion.Visible = false;
                lblupload.Visible = false;
 
            }
 
        }
 
        protected void DataGrid1_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            //if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.EditItem)
 
 
            int count = 0;
            string id;
            id = e.Item.Cells[0].Text;
 
 
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                try
                {
                    clientcon = objDB.getClientConnection(ClientConnect);
                    cmd = new SqlCommand("SELECT COUNT(*) FROM [ImageQuestion] WHERE Question_id = @QuestionId", clientcon);
                    cmd.Parameters.Add("@QuestionId", SqlDbType.Int).Value = Convert.ToInt32(id);
                    count = int.Parse(cmd.ExecuteScalar().ToString());
 
                    cmd.Dispose();
                    clientcon.Dispose();
                    clientcon.Close();
 
                    Image img_q = (Image)e.Item.FindControl("Img1");
 
                    if (count == 1)
                    {
                        img_q.Visible = true;
                    }
                    else
                    {
                        img_q.Visible = false;
                    }
                }
                catch { }
            }
 
 
            if (e.Item.ItemType == ListItemType.EditItem)
            {
                try
                {
 
                    clientcon = objDB.getClientConnection(ClientConnect);
                    cmd = new SqlCommand("SELECT COUNT(*) FROM [ImageQuestion] WHERE Question_id = @QuestionId", clientcon);
                    cmd.Parameters.Add("@QuestionId", SqlDbType.Int).Value = Convert.ToInt32(id);
                    count = int.Parse(cmd.ExecuteScalar().ToString());
 
                    cmd.Dispose();
                    clientcon.Dispose();
                    clientcon.Close();
 
                    Image img_e = (Image)e.Item.FindControl("Img2");
 
                    LinkButton lnkChage_e = (LinkButton)e.Item.FindControl("lnkChangeImage");
                    LinkButton lnkRemove_e = (LinkButton)e.Item.FindControl("lnkRemoveImage");
 
                    if (count == 1)
                    {
                        img_e.Visible = true;
                        lnkChage_e.Text = "Change";
                        lnkRemove_e.Visible = true;
 
                    }
                    else
                    {
                        img_e.Visible = false;
                        lnkChage_e.Text = "Add Image";
                        lnkRemove_e.Visible = false;
                    }
 
 
                }
                catch { }
 
            }
 
        }
 
        protected void lnkUp_Click(object sender, EventArgs e)
        {
            if (text == "Change")
            {
                ImageUpload_pop(qid);
            }
            else if (text == "Add Image")
            {
                ImageUpload_pop();
            }
 
            Binddata();
           
        }
 
        protected void lnkcan_Click(object sender, EventArgs e)
        {
            pnlPop.Visible = false;
            Modalpopupextender1.Hide();
        }
 
 
    }
}